<?php

namespace App\Modules\Inventory\Repositories;

use App\Modules\Inventory\Models\ItemCategory;
use App\Support\SelectOptionFormatter;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Collection;

class ItemCategoryRepository
{
    /**
     * @return LengthAwarePaginator<int, ItemCategory>
     */
    public function paginatedWithParent(int $perPage = 40): LengthAwarePaginator
    {
        return ItemCategory::query()
            ->with('parent')
            ->orderBy('code')
            ->paginate($perPage);
    }

    /**
     * @return array<int, string>
     */
    public function parentSelectOptions(): array
    {
        return ItemCategory::query()
            ->orderBy('code')
            ->get(['id', 'code', 'name'])
            ->mapWithKeys(fn (ItemCategory $c) => [$c->id => $c->code.' — '.$c->name])
            ->all();
    }

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

        if ($onlyId !== null) {
            $builder->whereKey($onlyId);
        } else {
            if ($excludeId !== null) {
                $builder->whereKeyNot($excludeId);
            }
            if ($query !== '') {
                $builder->where(function ($q) use ($query): void {
                    $q->where('name', 'like', '%'.$query.'%')
                        ->orWhere('code', 'like', '%'.$query.'%');
                });
            }
            $builder->limit($limit);
        }

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

    /**
     * @param  array<string, mixed>  $attributes
     */
    public function create(int $tenantId, array $attributes): ItemCategory
    {
        return ItemCategory::query()->create(array_merge(['tenant_id' => $tenantId], $attributes));
    }
}
