<?php

namespace App\Modules\Settings\Localization\Services;

use App\Modules\Settings\Localization\DTOs\LanguageData;
use App\Modules\Settings\Localization\Models\Language;
use App\Modules\Settings\Localization\Repositories\LanguageRepository;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;

class LanguageService
{
    public function __construct(
        private readonly LanguageRepository $repository,
    ) {}

    public function all(): Collection
    {
        return $this->repository->all();
    }

    public function allActive(): Collection
    {
        return $this->repository->allActive();
    }

    public function default(): ?Language
    {
        return $this->repository->default();
    }

    public function defaultCode(): string
    {
        return $this->default()?->code ?? config('app.fallback_locale', 'en');
    }

    public function findActiveByCode(string $code): ?Language
    {
        return $this->repository->findActiveByCode($code);
    }

    public function create(LanguageData $data): Language
    {
        return $this->repository->create($data->toArray());
    }

    public function update(Language $language, LanguageData $data): Language
    {
        $this->repository->update($language, $data->toArray());

        return $language->refresh();
    }

    public function toggleActive(Language $language): Language
    {
        if ($language->is_active && $language->is_default) {
            throw ValidationException::withMessages([
                'language' => [__('languages.errors.cannot_deactivate_default')],
            ]);
        }

        $this->repository->update($language, ['is_active' => ! $language->is_active]);

        return $language->refresh();
    }

    public function setDefault(Language $language): Language
    {
        DB::transaction(function () use ($language) {
            $this->repository->clearDefaultExcept($language->id);
            $this->repository->update($language, [
                'is_default' => true,
                'is_active' => true,
            ]);
        });

        return $language->refresh();
    }

    public function delete(Language $language): void
    {
        if ($language->is_default) {
            throw ValidationException::withMessages([
                'language' => [__('languages.errors.cannot_delete_default')],
            ]);
        }

        $this->repository->delete($language);
    }
}
