<?php

namespace App\Modules\Settings\Localization\Repositories;

use App\Modules\Settings\Localization\Models\Translation;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

class TranslationRepository
{
    /**
     * @return array<string, string>
     */
    public function mapForLocale(string $locale): array
    {
        return Translation::query()
            ->where('locale', $locale)
            ->pluck('value', 'key')
            ->all();
    }

    public function findByKeyAndLocale(string $key, string $locale): ?Translation
    {
        return Translation::query()
            ->where('key', $key)
            ->where('locale', $locale)
            ->first();
    }

    public function findOrFail(int $id): Translation
    {
        return Translation::query()->findOrFail($id);
    }

    public function create(array $data): Translation
    {
        return Translation::query()->create($data);
    }

    public function update(Translation $translation, array $data): bool
    {
        return $translation->update($data);
    }

    public function delete(Translation $translation): bool
    {
        return (bool) $translation->delete();
    }

    /**
     * @return array<int, string>
     */
    public function distinctGroups(): array
    {
        return Translation::query()
            ->distinct()
            ->orderBy('group')
            ->pluck('group')
            ->all();
    }

    /**
     * @param  array{group?: ?string, locale?: ?string, q?: ?string}  $filters
     */
    public function paginate(array $filters, int $perPage = 25): LengthAwarePaginator
    {
        return Translation::query()
            ->when($filters['group'] ?? null, fn ($q, $g) => $q->where('group', $g))
            ->when($filters['locale'] ?? null, fn ($q, $l) => $q->where('locale', $l))
            ->when($filters['q'] ?? null, fn ($q, $term) => $q->where(function ($sub) use ($term) {
                $sub->where('key', 'like', "%{$term}%")
                    ->orWhere('value', 'like', "%{$term}%");
            }))
            ->orderBy('group')
            ->orderBy('key')
            ->orderBy('locale')
            ->paginate($perPage)
            ->withQueryString();
    }
}
