<?php

namespace App\Modules\HR\Attendance\Repositories;

use App\Modules\HR\Attendance\Models\AttendanceCorrectionRequest;
use App\Modules\HR\Attendance\Support\AttendanceCorrectionStatus;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

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

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

    public function hasPendingForRecord(int $tenantId, int $attendanceRecordId): bool
    {
        return AttendanceCorrectionRequest::query()
            ->where('tenant_id', $tenantId)
            ->where('attendance_record_id', $attendanceRecordId)
            ->where('status', AttendanceCorrectionStatus::PENDING)
            ->exists();
    }

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

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

    public function paginateForTenant(
        int $tenantId,
        ?string $status,
        int $perPage = 25,
    ): LengthAwarePaginator {
        $q = AttendanceCorrectionRequest::query()
            ->where('tenant_id', $tenantId)
            ->with(['employee', 'attendanceRecord']);

        if ($status !== null && $status !== '') {
            $q->where('status', $status);
        }

        return $q->orderByDesc('created_at')->paginate($perPage);
    }

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

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