<?php

namespace App\Modules\HR\Recruitment\Repositories;

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

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

    /** @param  array<string, mixed>  $data */
    public function update(RecruitmentInterviewScorecard $row, array $data): RecruitmentInterviewScorecard
    {
        $row->update($data);

        return $row->fresh(['interview.application.candidate', 'scoredByUser']);
    }

    public function softDelete(RecruitmentInterviewScorecard $row): void
    {
        $row->delete();
    }

    /** @param  list<int>  $ids */
    public function softDeleteMany(int $tenantId, array $ids): int
    {
        return RecruitmentInterviewScorecard::query()
            ->where('tenant_id', $tenantId)
            ->whereIn('id', $ids)
            ->delete();
    }

    /**
     * @param  array{q?: ?string, recommendation?: ?string, interview_id?: ?int}  $filters
     */
    public function paginateForTenant(int $tenantId, array $filters = [], int $perPage = 20): LengthAwarePaginator
    {
        $q = RecruitmentInterviewScorecard::query()
            ->where('tenant_id', $tenantId)
            ->with(['interview.application.candidate', 'interview.application.vacancy', 'scoredByUser'])
            ->orderByDesc('id');

        if (! empty($filters['recommendation'])) {
            $q->where('recommendation', $filters['recommendation']);
        }
        if (! empty($filters['interview_id'])) {
            $q->where('interview_id', (int) $filters['interview_id']);
        }
        if (! empty($filters['q'])) {
            $term = '%'.$filters['q'].'%';
            $q->where(function ($b) use ($term): void {
                $b->where('reference_code', 'like', $term)
                    ->orWhereHas('interview', fn ($i) => $i->where('reference_code', 'like', $term));
            });
        }

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