<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Http\Resources\Api\UserResource;
use App\Models\User;
use App\Services\ActivityLogService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;

class AdminController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $this->authorizeSuperAdmin($request);

        $query = User::query()->whereIn('role', [User::ROLE_SUPER_ADMIN, User::ROLE_ADMIN]);

        if ($request->filled('role')) {
            $query->where('role', $request->role);
        }

        if ($request->filled('is_active')) {
            $query->where('is_active', $request->boolean('is_active'));
        }

        $perPage = min((int) $request->get('per_page', 15), 50);
        $admins = $query->orderBy('name')->paginate($perPage);

        return response()->json([
            'data' => UserResource::collection($admins->items()),
            'meta' => [
                'current_page' => $admins->currentPage(),
                'last_page' => $admins->lastPage(),
                'per_page' => $admins->perPage(),
                'total' => $admins->total(),
            ],
        ]);
    }

    public function store(Request $request): JsonResponse
    {
        $this->authorizeSuperAdmin($request);

        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'unique:users,email'],
            'password' => ['required', 'string', 'min:8'],
            'phone' => ['nullable', 'string', 'max:20'],
            'role' => ['required', 'string', Rule::in([User::ROLE_ADMIN, User::ROLE_SUPER_ADMIN])],
            'is_active' => ['sometimes', 'boolean'],
        ]);

        $admin = User::create([
            'name' => $validated['name'],
            'email' => $validated['email'],
            'password' => Hash::make($validated['password']),
            'phone' => $validated['phone'] ?? null,
            'role' => $validated['role'],
            'is_active' => $validated['is_active'] ?? true,
        ]);

        ActivityLogService::log(
            'admin.created',
            $admin,
            ['admin_id' => $admin->id, 'role' => $admin->role],
            "Admin créé : {$admin->name} ({$admin->role})",
            $request->user()?->id,
            $request
        );

        return response()->json([
            'data' => new UserResource($admin),
            'message' => __('Admin créé avec succès.'),
        ], 201);
    }

    public function update(Request $request, User $admin): JsonResponse
    {
        $this->authorizeSuperAdmin($request);

        // Empêcher la modification d'un super_admin par un admin normal
        if ($admin->isSuperAdmin() && !$request->user()->isSuperAdmin()) {
            abort(403, __('Vous ne pouvez pas modifier un super admin.'));
        }

        // Empêcher l'auto-désactivation
        if ($admin->id === $request->user()->id && $request->has('is_active') && !$request->boolean('is_active')) {
            return response()->json(['message' => __('Vous ne pouvez pas vous désactiver vous-même.')], 422);
        }

        $validated = $request->validate([
            'name' => ['sometimes', 'string', 'max:255'],
            'email' => ['sometimes', 'email', Rule::unique('users')->ignore($admin->id)],
            'password' => ['sometimes', 'string', 'min:8'],
            'phone' => ['nullable', 'string', 'max:20'],
            'role' => ['sometimes', 'string', Rule::in([User::ROLE_ADMIN, User::ROLE_SUPER_ADMIN])],
            'is_active' => ['sometimes', 'boolean'],
        ]);

        $oldData = $admin->toArray();

        if (isset($validated['password'])) {
            $validated['password'] = Hash::make($validated['password']);
        }

        $admin->update($validated);

        ActivityLogService::log(
            'admin.updated',
            $admin,
            ['before' => $oldData, 'after' => $admin->toArray()],
            "Admin modifié : {$admin->name}",
            $request->user()?->id,
            $request
        );

        return response()->json([
            'data' => new UserResource($admin->fresh()),
            'message' => __('Admin modifié avec succès.'),
        ]);
    }

    public function destroy(Request $request, User $admin): JsonResponse
    {
        $this->authorizeSuperAdmin($request);

        // Empêcher la suppression d'un super_admin par un admin normal
        if ($admin->isSuperAdmin() && !$request->user()->isSuperAdmin()) {
            abort(403, __('Vous ne pouvez pas supprimer un super admin.'));
        }

        // Empêcher l'auto-suppression
        if ($admin->id === $request->user()->id) {
            return response()->json(['message' => __('Vous ne pouvez pas vous supprimer vous-même.')], 422);
        }

        $name = $admin->name;
        $admin->delete();

        ActivityLogService::log(
            'admin.deleted',
            null,
            ['name' => $name, 'email' => $admin->email],
            "Admin supprimé : {$name}",
            $request->user()?->id,
            $request
        );

        return response()->json(['message' => __('Admin supprimé avec succès.')]);
    }

    protected function authorizeSuperAdmin(Request $request): void
    {
        $user = $request->user();
        if (!$user || !$user->isSuperAdmin()) {
            abort(403, __('Accès réservé aux super administrateurs.'));
        }
    }
}
