<?php

namespace App\Services;

use App\Events\UserFrozen;
use App\Models\User;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Hash;

class UserService
{
    public function list(User $requester, int $perPage = 15): LengthAwarePaginator
    {
        $query = User::with('createdBy:id,name')->latest();

        if (! $requester->isSuperAdmin()) {
            // Admin sees everyone except super_admin accounts
            $query->where('role', '!=', 'super_admin');
        }

        return $query->paginate($perPage);
    }

    public function create(array $data, User $createdBy): User
    {
        $role = $data['role'] ?? 'user';

        // Admin can only create users, enforce regardless of request payload
        if (! $createdBy->isSuperAdmin()) {
            $role = 'user';
        }

        return User::create([
            'name'       => $data['name'],
            'email'      => $data['email'],
            'password'   => Hash::make($data['password']),
            'role'       => $role,
            'phone'      => $data['phone'] ?? null,
            'created_by' => $createdBy->id,
        ]);
    }

    public function update(User $user, array $data, User $updatedBy): User
    {
        $payload = [];

        if (isset($data['name']))  $payload['name']  = $data['name'];
        if (isset($data['email'])) $payload['email'] = $data['email'];
        if (isset($data['phone'])) $payload['phone'] = $data['phone'];

        if (isset($data['role'])) {
            // Only super_admin can change roles
            if ($updatedBy->isSuperAdmin()) {
                $payload['role'] = $data['role'];
            }
        }

        if (! empty($data['password'])) {
            $payload['password'] = Hash::make($data['password']);
        }

        $user->update($payload);

        return $user->fresh();
    }

    public function delete(User $user): void
    {
        $user->tokens()->delete();
        $user->delete();
    }

    public function toggleFreeze(User $user): User
    {
        $user->update(['is_frozen' => ! $user->is_frozen]);

        if ($user->is_frozen) {
            $user->tokens()->delete();
            event(new UserFrozen($user));
        }

        return $user->fresh();
    }
}
