<?php

namespace App\Modules\HR\Recruitment\Repositories;

use App\Modules\HR\Recruitment\Models\RecruitmentInterview;
use App\Support\SelectOptionFormatter;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

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

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

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

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

    /** @param  list<int>  $ids */
    public function softDeleteMany(int $tenantId, array $ids): int
    {
        return RecruitmentInterview::query()
            ->where('tenant_id', $tenantId)
            ->whereIn('id', $ids)
            ->delete();
    }

    /**
     * @param  array{q?: ?string, status?: ?string, application_id?: ?int}  $filters
     */
    public function paginateForTenant(int $tenantId, array $filters = [], int $perPage = 20): LengthAwarePaginator
    {
        $q = RecruitmentInterview::query()
            ->where('tenant_id', $tenantId)
            ->with(['application.candidate', 'application.vacancy', 'interviewer'])
            ->orderByDesc('scheduled_at');

        if (! empty($filters['status'])) {
            $q->where('status', $filters['status']);
        }
        if (! empty($filters['application_id'])) {
            $q->where('application_id', (int) $filters['application_id']);
        }
        if (! empty($filters['q'])) {
            $term = '%'.$filters['q'].'%';
            $q->where(function ($b) use ($term): void {
                $b->where('reference_code', 'like', $term)
                    ->orWhere('location', 'like', $term)
                    ->orWhereHas('application', function ($a) use ($term): void {
                        $a->where('reference_code', 'like', $term)
                            ->orWhereHas('candidate', fn ($c) => $c
                                ->where('first_name', 'like', $term)
                                ->orWhere('last_name', '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 = RecruitmentInterview::query()
            ->where('tenant_id', $tenantId)
            ->with(['application.candidate'])
            ->orderByDesc('scheduled_at');

        if ($onlyId !== null) {
            $builder->whereKey($onlyId);
        } else {
            if ($query !== '') {
                $term = '%'.$query.'%';
                $builder->where(function ($b) use ($term): void {
                    $b->where('reference_code', 'like', $term);
                });
            }
            $builder->limit($limit);
        }

        $out = [];
        foreach ($builder->get() as $row) {
            $name = $row->application?->candidate?->full_name ?? '';
            $label = SelectOptionFormatter::label(
                trim($row->reference_code.($name !== '' ? ' — '.$name : '')),
                $row->scheduled_at?->format('Y-m-d H:i')
            );
            $out[] = ['value' => (string) $row->id, 'label' => $label];
        }

        return $out;
    }
}
