<?php

namespace App\Modules\HR\Recruitment\Repositories;

use App\Modules\HR\Recruitment\Models\RecruitmentApplication;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

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

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

        return $row->fresh(['vacancy', 'candidate', 'candidateCv']);
    }

    public function softDelete(RecruitmentApplication $row): void
    {
        $row->delete();
    }

    public function existsForVacancyCandidate(int $vacancyId, int $candidateId, ?int $exceptId = null): bool
    {
        $q = RecruitmentApplication::query()
            ->where('vacancy_id', $vacancyId)
            ->where('candidate_id', $candidateId);

        if ($exceptId !== null) {
            $q->whereKeyNot($exceptId);
        }

        return $q->exists();
    }

    /**
     * @param  array{q?: string|null, status?: string|null, vacancy_id?: int|null}  $filters
     */
    public function paginateForTenant(int $tenantId, array $filters = [], int $perPage = 20): LengthAwarePaginator
    {
        $q = RecruitmentApplication::query()
            ->where('tenant_id', $tenantId)
            ->with(['vacancy', 'candidate', 'candidateCv'])
            ->orderByDesc('id');

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

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

    /** @return list<array{value: string, label: string}> */
    public function searchForLookup(int $tenantId, string $query, int $limit = 30, ?int $onlyId = null): array
    {
        $builder = RecruitmentApplication::query()
            ->where('tenant_id', $tenantId)
            ->with(['candidate', 'vacancy'])
            ->orderByDesc('id');

        if ($onlyId !== null) {
            $builder->whereKey($onlyId);
        } else {
            if ($query !== '') {
                $term = '%'.$query.'%';
                $builder->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));
                });
            }
            $builder->limit($limit);
        }

        $out = [];
        foreach ($builder->get() as $row) {
            $label = $row->reference_code;
            $name = $row->candidate?->full_name;
            if ($name) {
                $label .= ' — '.$name;
            }
            if ($row->vacancy?->title) {
                $label .= ' / '.$row->vacancy->title;
            }
            $out[] = ['value' => (string) $row->id, 'label' => $label];
        }

        return $out;
    }
}
