<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\Database;
use Throwable;

/**
 * Redirections SEO (anciennes URLs -> nouvelles, ou 410).
 */
final class RedirectRepository
{
    /** @return array<string,mixed>|null */
    public static function find(string $path): ?array
    {
        try {
            $pdo  = Database::connection();
            $stmt = $pdo->prepare('SELECT * FROM redirects WHERE old_path = :p LIMIT 1');
            $stmt->execute(['p' => $path]);
            $row = $stmt->fetch();
            return $row === false ? null : $row;
        } catch (Throwable) {
            return null;
        }
    }

    /** @return list<array<string,mixed>> */
    public static function all(): array
    {
        $pdo = Database::connection();
        return $pdo->query('SELECT * FROM redirects ORDER BY old_path')->fetchAll();
    }

    public static function create(string $oldPath, string $newPath, int $code): void
    {
        $pdo = Database::connection();
        $pdo->prepare(
            'INSERT INTO redirects (old_path, new_path, code) VALUES (:o, :n, :c)
             ON DUPLICATE KEY UPDATE new_path = :n2, code = :c2'
        )->execute(['o' => $oldPath, 'n' => $newPath, 'c' => $code, 'n2' => $newPath, 'c2' => $code]);
    }

    public static function delete(int $id): void
    {
        Database::connection()->prepare('DELETE FROM redirects WHERE id = :id')->execute(['id' => $id]);
    }

    /** Normalise un chemin interne (« /slug », sans / final). */
    public static function normalizePath(string $path): string
    {
        $path = trim($path);
        if ($path === '') {
            return '';
        }
        if (!str_starts_with($path, '/') && !preg_match('#^https?://#i', $path)) {
            $path = '/' . $path;
        }
        if (str_starts_with($path, '/') && $path !== '/') {
            $path = rtrim($path, '/');
        }
        return $path;
    }
}
