<?php

namespace App\Modules\Settings\Localization\Repositories;

use App\Modules\Settings\Localization\Models\Language;
use Illuminate\Database\Eloquent\Collection;

class LanguageRepository
{
    public function all(): Collection
    {
        return Language::query()->orderByDesc('is_default')->orderBy('name')->get();
    }

    public function allActive(): Collection
    {
        return Language::query()->active()->orderByDesc('is_default')->orderBy('name')->get();
    }

    public function default(): ?Language
    {
        return Language::query()->default()->first();
    }

    public function findByCode(string $code): ?Language
    {
        return Language::query()->where('code', $code)->first();
    }

    public function findActiveByCode(string $code): ?Language
    {
        return Language::query()->active()->where('code', $code)->first();
    }

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

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

    public function delete(Language $language): bool
    {
        return (bool) $language->delete();
    }

    public function clearDefaultExcept(int $id): void
    {
        Language::query()
            ->where('id', '!=', $id)
            ->where('is_default', true)
            ->update(['is_default' => false]);
    }
}
