<?php

namespace App\Modules\HR\Recruitment\Repositories;

use App\Modules\HR\Recruitment\Models\RecruitmentOnboardingCase;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

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

    public function findForTenant(int $tenantId, int $id): ?RecruitmentOnboardingCase
    {
        return RecruitmentOnboardingCase::query()
            ->where('tenant_id', $tenantId)
            ->whereKey($id)
            ->first();
    }

    public function findByEmployee(int $tenantId, int $employeeId): ?RecruitmentOnboardingCase
    {
        return RecruitmentOnboardingCase::query()
            ->where('tenant_id', $tenantId)
            ->where('employee_id', $employeeId)
            ->first();
    }

    public function findWorkspace(int $tenantId, int $id): ?RecruitmentOnboardingCase
    {
        return RecruitmentOnboardingCase::query()
            ->where('tenant_id', $tenantId)
            ->whereKey($id)
            ->with([
                'employee.department',
                'employee.position',
                'hiring',
                'candidate',
                'vacancy',
                'application',
                'tasks.assignee',
                'tasks.attachments',
            ])
            ->first();
    }

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

        if (! empty($filters['status'])) {
            $q->where('status', $filters['status']);
        }
        if (! empty($filters['q'])) {
            $term = '%'.$filters['q'].'%';
            $q->where(function ($b) use ($term): void {
                $b->where('reference_code', 'like', $term)
                    ->orWhereHas('employee', fn ($e) => $e
                        ->where('full_name', 'like', $term)
                        ->orWhere('employee_code', 'like', $term));
            });
        }

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

    /** @param  array<string, mixed>  $data */
    public function update(RecruitmentOnboardingCase $case, array $data): RecruitmentOnboardingCase
    {
        $case->fill($data)->save();

        return $case->refresh();
    }
}
