<?php

namespace App\Modules\HR\Shifts\Repositories;

use App\Modules\HR\Shifts\Models\Shift;
use App\Support\SelectOptionFormatter;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Collection;

class ShiftRepository
{
    public function paginateForTenant(int $tenantId, int $perPage = 20): LengthAwarePaginator
    {
        return Shift::query()
            ->where('tenant_id', $tenantId)
            ->orderBy('name')
            ->paginate($perPage);
    }

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

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

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

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

        return $shift->fresh();
    }

    /**
     * @return list<array{value: string, label: string}>
     */
    public function searchForLookup(
        int $tenantId,
        string $query,
        int $limit = 30,
        ?int $onlyId = null,
    ): array {
        $builder = Shift::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',
        );
    }
}
