<?php

namespace App\Modules\HR\Leave\Repositories;

use App\Modules\HR\Leave\Models\LeaveType;
use App\Support\SelectOptionFormatter;
use Illuminate\Database\Eloquent\Collection;

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

    /**
     * @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',
        );
    }
}
