<?php

namespace App\Http\Controllers\Superadmin;

use App\DTOs\SuperAdmin\SectionRuleDto;
use App\Http\Controllers\Controller;
use App\Http\Requests\SuperAdmin\SectionRuleRequest;
use App\Services\SectionRuleService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class SectionRuleController extends Controller
{
    public function __construct(protected SectionRuleService $sectionRuleService)
    {
    }

    public function index(Request $request): View
    {
        $perPage = $request->get('per_page', 10);
        $rules = $this->sectionRuleService->getPaginated($perPage);
        return view('superadmin.section-rules.index', compact('rules'));
    }

    public function create(): View
    {
        return view('superadmin.section-rules.create');
    }

    public function store(SectionRuleRequest $request): RedirectResponse
    {
        $dto = new SectionRuleDto($request->validated());
        $created = $this->sectionRuleService->create($dto);

        if ($created) {
            return redirect()
                ->route('superadmin.section-rules.index')
                ->with('success', 'Regla creada correctamente.');
        }

        return back()->with('error', 'No se pudo crear la regla.')->withInput();
    }

    public function show(int $id): View
    {
        $dto = $this->sectionRuleService->find($id);
        if (!$dto) {
            abort(404);
        }

        return view('superadmin.section-rules.show', compact('dto', 'id'));
    }

    public function edit(int $id): View
    {
        $dto = $this->sectionRuleService->find($id);
        if (!$dto) {
            abort(404);
        }

        return view('superadmin.section-rules.edit', compact('dto', 'id'));
    }

    public function update(SectionRuleRequest $request, int $id): RedirectResponse
    {
        $dto = new SectionRuleDto($request->validated());
        $updated = $this->sectionRuleService->update($id, $dto);

        if ($updated) {
            return redirect()
                ->route('superadmin.section-rules.index')
                ->with('success', 'Regla actualizada correctamente.');
        }

        return back()->with('error', 'No se pudo actualizar la regla.')->withInput();
    }

    public function destroy(int $id): RedirectResponse
    {
        $deleted = $this->sectionRuleService->delete($id);

        if ($deleted) {
            return redirect()
                ->route('superadmin.section-rules.index')
                ->with('success', 'Regla eliminada correctamente.');
        }

        return back()->with('error', 'No se pudo eliminar la regla.');
    }
}
