<?php

namespace App\Modules\HR\Shifts\Repositories;

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

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

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

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

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

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