<?php

namespace App\Modules\HR\Recruitment\Repositories;

use App\Modules\HR\Recruitment\Models\RecruitmentHiring;
use App\Modules\HR\Recruitment\Models\RecruitmentOfferLetter;
use App\Modules\HR\Recruitment\Support\OfferLetterStatus;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

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

    /**
     * @param  array{q?: ?string}  $filters
     */
    public function paginateAcceptedOffers(int $tenantId, array $filters = [], int $perPage = 20): LengthAwarePaginator
    {
        $q = RecruitmentOfferLetter::query()
            ->where('tenant_id', $tenantId)
            ->where('status', OfferLetterStatus::ACCEPTED)
            ->whereNull('employee_id')
            ->with(['candidate', 'vacancy', 'department', 'position', 'application'])
            ->orderByDesc('accepted_at')
            ->orderByDesc('id');

        if (! empty($filters['q'])) {
            $term = '%'.$filters['q'].'%';
            $q->where(function ($b) use ($term): void {
                $b->where('reference_code', 'like', $term)
                    ->orWhereHas('candidate', fn ($c) => $c
                        ->where('first_name', 'like', $term)
                        ->orWhere('last_name', 'like', $term)
                        ->orWhere('email', 'like', $term));
            });
        }

        return $q->paginate($perPage)->withQueryString();
    }

    public function findHiringForOffer(int $tenantId, int $offerId): ?RecruitmentHiring
    {
        return RecruitmentHiring::query()
            ->where('tenant_id', $tenantId)
            ->where('offer_letter_id', $offerId)
            ->first();
    }
}
