<?php

namespace App\Modules\HR\PermissionRequests\Repositories;

use App\Modules\HR\PermissionRequests\Models\PermissionRequest;
use App\Modules\HR\PermissionRequests\Support\PermissionRequestStatus;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

class PermissionRequestRepository
{
    /**
     * @param  array<string, mixed>  $data
     */
    public function create(array $data): PermissionRequest
    {
        return PermissionRequest::query()->create($data);
    }

    public function findForTenant(int $tenantId, int $id): ?PermissionRequest
    {
        return PermissionRequest::query()
            ->where('tenant_id', $tenantId)
            ->whereKey($id)
            ->first();
    }

    public function lockForTenant(int $tenantId, int $id): ?PermissionRequest
    {
        return PermissionRequest::query()
            ->where('tenant_id', $tenantId)
            ->whereKey($id)
            ->lockForUpdate()
            ->first();
    }

    public function paginateForTenant(int $tenantId, int $perPage = 20): LengthAwarePaginator
    {
        return PermissionRequest::query()
            ->where('tenant_id', $tenantId)
            ->with(['employee'])
            ->orderByDesc('created_at')
            ->paginate($perPage);
    }

    public function paginateForEmployee(int $tenantId, int $employeeId, int $perPage = 20): LengthAwarePaginator
    {
        return PermissionRequest::query()
            ->where('tenant_id', $tenantId)
            ->where('employee_id', $employeeId)
            ->orderByDesc('created_at')
            ->paginate($perPage);
    }

    public function countPendingForTenant(int $tenantId): int
    {
        return PermissionRequest::query()
            ->where('tenant_id', $tenantId)
            ->where('status', PermissionRequestStatus::PENDING)
            ->count();
    }

    /**
     * @param  array<string, mixed>  $data
     */
    public function update(PermissionRequest $row, array $data): PermissionRequest
    {
        $row->update($data);

        return $row->fresh(['employee']);
    }
}
