<?php

namespace App\Repositories;

use App\Models\User;

class UserRepository extends BaseRepository
{
    protected $model;

    public function __construct()
    {
        $this->model = new User();
    }

    public function getAllByOrganization(?string $orgHex)
    {
        $query = $this->model->query();
        return $this->applyOrganizationScope($query, $orgHex)->orderBy('name')->get();
    }

    public function getByIdInOrganization(string $id, ?string $orgHex)
    {
        $query = $this->model->where('id', $this->normalizeId($id));
        return $this->applyOrganizationScope($query, $orgHex)->first();
    }

    public function create(array $data)
    {
        return $this->model->create($data);
    }

    public function updateInOrganization(string $id, array $data, ?string $orgHex)
    {
        $query = $this->model->where('id', $this->normalizeId($id));
        $user = $this->applyOrganizationScope($query, $orgHex)->first();

        if ($user) {
            $user->update($data);
        }

        return $user;
    }

    public function updatePasswordInOrganization(string $id, string $hashedPassword, ?string $orgHex)
    {
        return $this->updateInOrganization($id, ['password' => $hashedPassword], $orgHex);
    }

    public function deleteInOrganization(string $id, ?string $orgHex)
    {
        $query = $this->model->where('id', $this->normalizeId($id));
        return $this->applyOrganizationScope($query, $orgHex)->delete();
    }

    public function paginateFilteredByOrganization(?string $orgHex, array $filters, int $perPage = 10)
    {
        $safePerPage = max(1, min(100, $perPage));

        $query = $this->model->query()->with('role');
        $query = $this->applyOrganizationScope($query, $orgHex);

        $keyword = trim((string)($filters['keyword'] ?? ''));
        if ($keyword !== '') {
            $like = '%' . $keyword . '%';
            $query->where(function ($q) use ($like) {
                $q->where('name', 'LIKE', $like)
                    ->orWhere('display_name', 'LIKE', $like)
                    ->orWhere('email', 'LIKE', $like);
            });
        }

        $query->orderBy('created_at', 'desc');

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