<?php

namespace App\Modules\HR\Leave\Repositories;

use App\Modules\HR\Leave\Models\LeaveType;
use App\Support\Lists\ListQuery;
use App\Support\SelectOptionFormatter;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;

class LeaveTypeRepository
{
    /**
     * @return Collection<int, LeaveType>
     */
    public function listForTenant(int $tenantId): Collection
    {
        return LeaveType::query()
            ->where('tenant_id', $tenantId)
            ->orderBy('name')
            ->get();
    }

    public function paginateForIndex(int $tenantId, Request $request): LengthAwarePaginator
    {
        $query = LeaveType::query()->where('tenant_id', $tenantId);

        ListQuery::applySearch($query, $request->input('q'), ['name']);
        ListQuery::applyBoolean($query, 'is_active', $request->input('is_active'));
        ListQuery::applyBoolean($query, 'is_paid', $request->input('is_paid'));
        ListQuery::applySort(
            $query,
            $request->input('sort'),
            $request->input('dir'),
            [
                'name' => 'name',
                'annual_limit' => 'annual_limit',
                'is_active' => 'is_active',
            ],
            'name',
        );

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

    /**
     * @return Collection<int, LeaveType>
     */
    public function activeForTenant(int $tenantId): Collection
    {
        return LeaveType::query()
            ->where('tenant_id', $tenantId)
            ->where('is_active', true)
            ->orderBy('name')
            ->get();
    }

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

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

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

        return $type->fresh();
    }

    /**
     * @param  list<array{name: string, is_paid: bool, annual_limit: int|null, requires_approval: bool}>  $defaults
     */
    public function seedDefaults(int $tenantId, array $defaults): void
    {
        foreach ($defaults as $row) {
            LeaveType::query()->firstOrCreate(
                [
                    'tenant_id' => $tenantId,
                    'name' => $row['name'],
                ],
                [
                    'is_paid' => $row['is_paid'],
                    'annual_limit' => $row['annual_limit'] ?? null,
                    'requires_approval' => $row['requires_approval'],
                    'is_active' => true,
                ],
            );
        }
    }

    /**
     * @return list<array{value: string, label: string}>
     */
    public function searchForLookup(
        int $tenantId,
        string $query,
        int $limit = 30,
        ?int $onlyId = null,
    ): array {
        $builder = LeaveType::query()
            ->where('tenant_id', $tenantId)
            ->where('is_active', true)
            ->orderBy('name');

        if ($onlyId !== null) {
            $builder->whereKey($onlyId);
        } else {
            if ($query !== '') {
                $builder->where('name', 'like', '%'.$query.'%');
            }
            $builder->limit($limit);
        }

        return SelectOptionFormatter::mapRows(
            $builder->get(['id', 'name']),
            'name',
        );
    }
}
