<?php

namespace App\Modules\HR\Recruitment\Services;

use App\Modules\HR\Recruitment\DTOs\RecruitmentReportFilters;
use App\Modules\HR\Recruitment\Models\RecruitmentReportSavedFilter;
use App\Modules\HR\Recruitment\Repositories\RecruitmentReportSavedFilterRepository;
use App\Modules\HR\Recruitment\Support\RecruitmentReportType;
use Illuminate\Validation\ValidationException;

class RecruitmentReportSavedFilterService
{
    public function __construct(
        private readonly RecruitmentReportSavedFilterRepository $repository,
    ) {}

    public function store(
        int $tenantId,
        int $userId,
        string $reportType,
        string $name,
        RecruitmentReportFilters $filters,
        bool $isDefault = false,
    ): RecruitmentReportSavedFilter {
        abort_unless(RecruitmentReportType::isValid($reportType), 404);
        if ($isDefault) {
            $this->repository->clearDefaults($tenantId, $userId, $reportType);
        }

        return $this->repository->create([
            'tenant_id' => $tenantId,
            'user_id' => $userId,
            'name' => $name,
            'report_type' => $reportType,
            'filters' => $filters->toQuery(),
            'is_default' => $isDefault,
        ]);
    }

    public function destroy(int $tenantId, int $userId, int $id): void
    {
        $row = $this->repository->findOwned($tenantId, $userId, $id);
        if ($row === null) {
            throw ValidationException::withMessages([
                'filter' => [__('recruitment.reports.errors.filter_not_found')],
            ]);
        }
        $this->repository->deleteOwned($tenantId, $userId, $id);
    }

    public function findOwned(int $tenantId, int $userId, int $id): RecruitmentReportSavedFilter
    {
        $row = $this->repository->findOwned($tenantId, $userId, $id);
        abort_if($row === null, 404);

        return $row;
    }
}
