<?php

declare(strict_types=1);

namespace App\Controllers\Admin;

use App\Core\Request;
use App\Core\Response;
use App\Core\Session;
use App\Core\View;
use App\Models\RedirectRepository;

final class RedirectController extends AdminController
{
    /** @param array<string,string> $params */
    public function index(Request $request, array $params): Response
    {
        if ($r = $this->guard()) {
            return $r;
        }

        return Response::html(View::render('admin/redirects/index', [
            'pageTitle' => 'Redirections',
            'redirects' => RedirectRepository::all(),
            'flash'     => Session::pull('flash'),
            'errors'    => (array) (Session::pull('flash_errors') ?? []),
        ], 'layouts/admin'));
    }

    /** @param array<string,string> $params */
    public function store(Request $request, array $params): Response
    {
        if ($r = $this->guard()) {
            return $r;
        }
        $back = Response::redirect(base_url('admin/redirects'));
        if (!$this->csrfValid($request)) {
            return $back;
        }

        $old  = RedirectRepository::normalizePath((string) $request->input('old_path', ''));
        $new  = RedirectRepository::normalizePath((string) $request->input('new_path', ''));
        $code = (int) $request->input('code', 301);
        if (!in_array($code, [301, 302, 410], true)) {
            $code = 301;
        }

        $errors = [];
        if ($old === '' || !str_starts_with($old, '/') || $old === '/') {
            $errors[] = 'Ancien chemin invalide (ex. /ancienne-url).';
        }
        if ($code !== 410 && $new === '') {
            $errors[] = 'Nouvelle cible requise (sauf code 410).';
        }

        if ($errors !== []) {
            Session::set('flash_errors', $errors);
            return $back;
        }

        RedirectRepository::create($old, $code === 410 ? '' : $new, $code);
        Session::set('flash', 'Redirection enregistrée.');

        return $back;
    }

    /** @param array<string,string> $params */
    public function destroy(Request $request, array $params): Response
    {
        if ($r = $this->guard()) {
            return $r;
        }
        if ($this->csrfValid($request)) {
            RedirectRepository::delete((int) ($params['id'] ?? 0));
            Session::set('flash', 'Redirection supprimée.');
        }

        return Response::redirect(base_url('admin/redirects'));
    }
}
