<?php

namespace App\Modules\HR\Recruitment\Services;

use App\Modules\HR\Recruitment\Models\RecruitmentVacancy;
use App\Modules\HR\Recruitment\Repositories\RecruitmentVacancyRepository;
use App\Modules\HR\Recruitment\Support\VacancyStatus;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;

class CareerPortalVacancyService
{
    public function __construct(
        private readonly RecruitmentVacancyRepository $repository,
        private readonly RecruitmentVacancyService $vacancies,
    ) {}

    public function publishToPortal(RecruitmentVacancy $row): RecruitmentVacancy
    {
        if ($row->status === VacancyStatus::DRAFT) {
            $row = $this->vacancies->publish($row);
        }
        if ($row->status !== VacancyStatus::OPEN) {
            throw ValidationException::withMessages([
                'status' => __('recruitment.career_portal.errors.only_open_on_portal'),
            ]);
        }

        return $this->repository->update($row, [
            'show_on_portal' => true,
            'slug' => $row->slug ?: $this->uniqueSlug((int) $row->tenant_id, (string) $row->title, (int) $row->id),
            'published_at' => $row->published_at ?? now(),
        ]);
    }

    public function unpublishFromPortal(RecruitmentVacancy $row): RecruitmentVacancy
    {
        return $this->repository->update($row, ['show_on_portal' => false]);
    }

    public function toggleFeatured(RecruitmentVacancy $row, bool $featured): RecruitmentVacancy
    {
        return $this->repository->update($row, ['is_featured' => $featured]);
    }

    /** @param  array{seo_title?: ?string, seo_description?: ?string, seo_keywords?: ?string, is_featured?: bool}  $data */
    public function updatePortalMeta(RecruitmentVacancy $row, array $data): RecruitmentVacancy
    {
        return $this->repository->update($row, [
            'seo_title' => $data['seo_title'] ?? $row->seo_title,
            'seo_description' => $data['seo_description'] ?? $row->seo_description,
            'seo_keywords' => $data['seo_keywords'] ?? $row->seo_keywords,
            'is_featured' => array_key_exists('is_featured', $data)
                ? (bool) $data['is_featured']
                : (bool) $row->is_featured,
        ]);
    }

    private function uniqueSlug(int $tenantId, string $title, int $id): string
    {
        $base = Str::slug($title) ?: 'job-'.$id;
        $slug = $base;
        $i = 1;
        while (
            RecruitmentVacancy::query()
                ->where('tenant_id', $tenantId)
                ->where('slug', $slug)
                ->whereKeyNot($id)
                ->exists()
        ) {
            $slug = $base.'-'.$i;
            $i++;
        }

        return $slug;
    }
}
