<?php

namespace App\Modules\HR\Performance\Repositories;

use App\Modules\HR\Performance\Models\PerformanceCycle;
use App\Modules\HR\Performance\Models\PerformanceReview;

class PerformanceRepository
{
    public function cycles(int $tenant)
    {
        return PerformanceCycle::query()->where('tenant_id', $tenant)->latest()->paginate();
    }

    public function reviews(int $tenant, ?int $employee = null)
    {
        return PerformanceReview::query()->with(['employee:id,full_name', 'cycle:id,name'])
            ->where('tenant_id', $tenant)
            ->when($employee, fn ($q) => $q->where('employee_id', $employee))->latest()->paginate();
    }

    public function cycleOptions(int $tenant): array
    {
        return PerformanceCycle::query()->where('tenant_id', $tenant)
            ->orderByDesc('starts_at')->pluck('name', 'id')->all();
    }

    public function saveCycle(int $tenant, array $data, ?PerformanceCycle $cycle = null): PerformanceCycle
    {
        $cycle ??= new PerformanceCycle(['tenant_id' => $tenant]);
        $cycle->fill($data)->save();

        return $cycle;
    }

    public function saveReview(int $tenant, array $data, ?PerformanceReview $review = null): PerformanceReview
    {
        $review ??= new PerformanceReview(['tenant_id' => $tenant]);
        $review->fill($data)->save();

        return $review;
    }

    public function deleteCycle(PerformanceCycle $cycle): void
    {
        $cycle->delete();
    }

    public function deleteReview(PerformanceReview $review): void
    {
        $review->delete();
    }
}
