<?php

namespace Modules\Auth\Repositories;

use App\Models\User;
use Modules\Auth\DTO\UserListFilter;
use Illuminate\Support\Facades\Hash;
use Modules\Core\Enums\StatusEnum;

class UserRepository
{
    public function getUsers(UserListFilter $filters, bool $includeSuperAdmin = true, array $columns = ['*'])
    {
        return User::query()
            ->select($columns)
            ->with('roles:id,name,title')
            ->filterId($filters->id)
            ->filterStatus($filters->status)
            ->search($filters->search)
            ->when(!$includeSuperAdmin, fn ($q) => $q->excludeSuperAdmin())
            ->when($filters->role, fn ($q) => $q->role($filters->role))
            ->orderBy('userId')
            ->paginate($filters->perPage);
    }

    public function createUser(array $data): User
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'phone' => $data['phone'],
            'password' => Hash::make($data['password']),
            'status' => $data['status'] ?? StatusEnum::INACTIVE
        ]);
    }

    public function find(int $id, array $columns = ['*']): User
    {
        return User::select($columns)->findOrFail($id);
    }

    public function updateUser(User $user, array $data): User
    {
        $user->update($data);

        return $user;
    }

    public function updateStatus(User $user, $status): User
    {
        $user->update([
            'status' => $status
        ]);

        return $user;
    }
}
