<?php

namespace App\Modules\HR\Recruitment\Repositories;

use App\Modules\HR\Recruitment\Models\RecruitmentApplication;
use App\Modules\HR\Recruitment\Models\RecruitmentVacancy;
use App\Modules\HR\Recruitment\Support\VacancyStatus;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;

class CareerPortalVacancyRepository
{
    /**
     * @param  array{q?: ?string, featured?: bool}  $filters
     */
    public function paginatePublished(int $tenantId, array $filters = [], int $perPage = 12): LengthAwarePaginator
    {
        $q = $this->publishedQuery($tenantId)->with(['department', 'position']);

        if (! empty($filters['featured'])) {
            $q->where('is_featured', true);
        }
        if (! empty($filters['q'])) {
            $term = '%'.$filters['q'].'%';
            $q->where(function ($b) use ($term): void {
                $b->where('title', 'like', $term)
                    ->orWhere('description', 'like', $term);
            });
        }

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

    /** @return Collection<int, RecruitmentVacancy> */
    public function featured(int $tenantId, int $limit = 6): Collection
    {
        return $this->publishedQuery($tenantId)
            ->where('is_featured', true)
            ->with(['department', 'position'])
            ->limit($limit)
            ->get();
    }

    public function findPublishedBySlug(int $tenantId, string $slug): ?RecruitmentVacancy
    {
        return $this->publishedQuery($tenantId)
            ->where('slug', $slug)
            ->with(['department', 'position'])
            ->first();
    }

    public function findByTrackingToken(int $tenantId, string $token): ?RecruitmentApplication
    {
        return RecruitmentApplication::query()
            ->where('tenant_id', $tenantId)
            ->where('tracking_token', $token)
            ->with([
                'candidate.cvs',
                'vacancy.department',
                'vacancy.position',
                'interviews',
                'offerLetters',
            ])
            ->first();
    }

    private function publishedQuery(int $tenantId)
    {
        return RecruitmentVacancy::query()
            ->where('tenant_id', $tenantId)
            ->where('status', VacancyStatus::OPEN)
            ->where('show_on_portal', true)
            ->where(function ($q): void {
                $q->whereNull('closes_at')->orWhereDate('closes_at', '>=', now()->toDateString());
            })
            ->orderByDesc('is_featured')
            ->orderByDesc('published_at');
    }
}
