<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Http\Requests\User\StoreUserRequest;
use App\Http\Requests\User\UpdateUserRequest;
use App\Models\User;
use App\Services\UserService;
use App\Traits\ApiResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class UserController extends Controller
{
    use ApiResponse;

    public function __construct(private readonly UserService $userService) {}

    public function index(Request $request): JsonResponse
    {
        $perPage = (int) $request->query('per_page', 15);
        $users   = $this->userService->list($request->user(), $perPage);

        return $this->success($users, 'Users retrieved');
    }

    public function store(StoreUserRequest $request): JsonResponse
    {
        $user = $this->userService->create($request->validated(), $request->user());

        return $this->created(
            $user->load('createdBy:id,name'),
            'User created successfully'
        );
    }

    public function show(int $id): JsonResponse
    {
        $user = User::with('createdBy:id,name')->findOrFail($id);

        return $this->success($user, 'User retrieved');
    }

    public function update(UpdateUserRequest $request, int $id): JsonResponse
    {
        $user    = User::findOrFail($id);
        $updated = $this->userService->update($user, $request->validated(), $request->user());

        return $this->success(
            $updated->load('createdBy:id,name'),
            'User updated successfully'
        );
    }

    public function destroy(Request $request, int $id): JsonResponse
    {
        $requester = $request->user();

        if (! $requester->hasAdminAccess()) {
            return $this->forbidden();
        }

        $user = User::findOrFail($id);

        if ($user->id === $requester->id) {
            return $this->error('You cannot delete your own account.', 422);
        }

        // Protect super_admin accounts from being deleted by admins
        if (! $requester->isSuperAdmin() && $user->isSuperAdmin()) {
            return $this->forbidden('Cannot delete a Super Admin account.');
        }

        // Admin can only delete user-role accounts
        if ($requester->isAdmin() && $user->role !== 'user') {
            return $this->forbidden('Admins can only delete user accounts.');
        }

        $this->userService->delete($user);

        return $this->noContent('User deleted successfully');
    }

    public function toggleFreeze(Request $request, int $id): JsonResponse
    {
        $requester = $request->user();

        if (! $requester->hasAdminAccess()) {
            return $this->forbidden();
        }

        $user = User::findOrFail($id);

        if ($user->id === $requester->id) {
            return $this->error('You cannot freeze your own account.', 422);
        }

        // Admin cannot freeze other admins or super_admin
        if ($requester->isAdmin() && $user->role !== 'user') {
            return $this->forbidden('Admins can only freeze user accounts.');
        }

        // No one can freeze a super_admin
        if ($user->isSuperAdmin()) {
            return $this->forbidden('Super Admin account cannot be frozen.');
        }

        $updated = $this->userService->toggleFreeze($user);
        $action  = $updated->is_frozen ? 'frozen' : 'unfrozen';

        return $this->success($updated, "User {$action} successfully");
    }
}
