<?php

namespace App\Modules\HR\Offboarding\Repositories;

use App\Modules\HR\Employees\Models\EmployeeAssetAssignment;
use App\Modules\HR\Offboarding\Models\OffboardingCase;
use App\Support\Lists\ListQuery;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Http\Request;

class OffboardingRepository
{
    public function paginate(int $tenant)
    {
        return OffboardingCase::query()->with(['employee:id,full_name', 'checklistItems'])
            ->where('tenant_id', $tenant)->latest()->paginate();
    }

    public function paginateForIndex(int $tenant, Request $request): LengthAwarePaginator
    {
        $query = OffboardingCase::query()
            ->with(['employee:id,full_name', 'checklistItems'])
            ->where('tenant_id', $tenant);

        ListQuery::applyEquals($query, 'employee_id', $request->input('employee_id'));
        ListQuery::applyEquals($query, 'type', $request->input('type'));
        ListQuery::applyEquals($query, 'status', $request->input('status'));
        ListQuery::applyDateFrom($query, 'last_working_date', $request->input('last_working_date_from'));
        ListQuery::applyDateTo($query, 'last_working_date', $request->input('last_working_date_to'));
        ListQuery::applySort(
            $query,
            $request->input('sort'),
            $request->input('dir'),
            [
                'last_working_date' => 'last_working_date',
                'status' => 'status',
                'type' => 'type',
            ],
            'id',
            'desc',
        );

        return ListQuery::paginate($query, $request);
    }

    public function create(array $data): OffboardingCase
    {
        return OffboardingCase::query()->create($data);
    }

    public function update(OffboardingCase $case, array $data): OffboardingCase
    {
        $case->update($data);

        return $case->fresh(['employee', 'checklistItems']);
    }

    public function returnAssets(int $tenant, int $employee): void
    {
        EmployeeAssetAssignment::query()->where('tenant_id', $tenant)->where('employee_id', $employee)
            ->whereNull('returned_at')->update(['status' => 'returned', 'returned_at' => now()->toDateString()]);
    }
}
