<?php

namespace App\Modules\Settings\Localization\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Settings\Localization\DTOs\LanguageData;
use App\Modules\Settings\Localization\Models\Language;
use App\Modules\Settings\Localization\Requests\StoreLanguageRequest;
use App\Modules\Settings\Localization\Requests\UpdateLanguageRequest;
use App\Modules\Settings\Localization\Services\LanguageService;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class LanguageController extends Controller
{
    public function __construct(
        private readonly LanguageService $service,
    ) {}

    public function index(): View
    {
        return view('pages.settings.languages.index', [
            'languages' => $this->service->all(),
        ]);
    }

    public function create(): View
    {
        return view('pages.settings.languages.create');
    }

    public function store(StoreLanguageRequest $request): RedirectResponse
    {
        $this->service->create(LanguageData::fromValidated($request->validated()));

        return redirect()
            ->route('settings.languages.index')
            ->with('status', __('languages.flash.created'));
    }

    public function edit(Language $language): View
    {
        return view('pages.settings.languages.edit', ['language' => $language]);
    }

    public function update(UpdateLanguageRequest $request, Language $language): RedirectResponse
    {
        $this->service->update($language, LanguageData::fromValidated($request->validated()));

        return redirect()
            ->route('settings.languages.index')
            ->with('status', __('languages.flash.updated'));
    }

    public function setDefault(Language $language): RedirectResponse
    {
        $this->service->setDefault($language);

        return back()->with('status', __('languages.flash.default_set', ['name' => $language->name]));
    }

    public function toggleActive(Language $language): RedirectResponse
    {
        $this->service->toggleActive($language);

        return back()->with('status', __('languages.flash.updated'));
    }

    public function destroy(Language $language): RedirectResponse
    {
        $this->service->delete($language);

        return redirect()
            ->route('settings.languages.index')
            ->with('status', __('languages.flash.deleted'));
    }
}
