<?php

namespace App\Modules\HR\Recruitment\Services;

use App\Modules\HR\Recruitment\Models\RecruitmentCareerPortalSetting;
use App\Modules\HR\Recruitment\Repositories\CareerPortalSettingsRepository;
use App\Modules\HR\Recruitment\Support\RecruitmentTenantId;

class CareerPortalSettingsService
{
    public function __construct(
        private readonly CareerPortalSettingsRepository $repository,
    ) {}

    public function getOrDefaults(?int $tenantId = null): RecruitmentCareerPortalSetting
    {
        $tenantId = $tenantId ?? RecruitmentTenantId::require();
        $row = $this->repository->findForTenant($tenantId);
        if ($row !== null) {
            return $row;
        }

        $row = new RecruitmentCareerPortalSetting([
            'tenant_id' => $tenantId,
            'is_enabled' => false,
            'portal_title' => __('recruitment.career_portal.defaults.title'),
            'portal_subtitle' => __('recruitment.career_portal.defaults.subtitle'),
            'recaptcha_enabled' => false,
        ]);
        $row->exists = false;

        return $row;
    }

    /** @param  array<string, mixed>  $data */
    public function save(array $data, ?int $tenantId = null): RecruitmentCareerPortalSetting
    {
        return $this->repository->upsert($tenantId ?? RecruitmentTenantId::require(), [
            'is_enabled' => (bool) ($data['is_enabled'] ?? false),
            'portal_title' => $data['portal_title'] ?? null,
            'portal_subtitle' => $data['portal_subtitle'] ?? null,
            'about_text' => $data['about_text'] ?? null,
            'contact_email' => $data['contact_email'] ?? null,
            'contact_phone' => $data['contact_phone'] ?? null,
            'seo_title' => $data['seo_title'] ?? null,
            'seo_description' => $data['seo_description'] ?? null,
            'seo_keywords' => $data['seo_keywords'] ?? null,
            'recaptcha_enabled' => (bool) ($data['recaptcha_enabled'] ?? false),
        ]);
    }
}
