<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

class ReleaseWindow
{
    public function handle(Request $request, Closure $next, string $type)
    {
        $tz = config('release.timezone', 'America/Sao_Paulo');
        $now = Carbon::now($tz);

        $index = $this->resolveIndex($request, $type);

        $fallback = match ($type) {
            'modulo'   => url('/modulos'),
            'minuto'   => route('minutos'),
            'pergunta' => route('diarias'),
            default    => url('/dashboard'),
        };

        if ($index === null) {
            return redirect($fallback)->with('warning', 'Conteúdo indisponível no momento.');
        }

        $cfg = config("release.$type.$index");
        if (!$cfg) {
            return redirect($fallback)->with('warning', 'Conteúdo indisponível no momento.');
        }

        $releaseAt = Carbon::parse($cfg['release_at'], $tz);
        $ttl = $cfg['ttl_hours'] ?? null;

        $available = $now->greaterThanOrEqualTo($releaseAt)
            && ($ttl === null || $now->lessThan($releaseAt->copy()->addHours($ttl)));

        if ($available) {
            return $next($request);
        }

        $message = $now->lt($releaseAt)
            ? 'Conteúdo disponível em ' . $releaseAt->format('d/m/Y H:i') . '.'
            : 'Janela encerrada em ' . $releaseAt->copy()->addHours((int)$ttl)->format('d/m/Y H:i') . '.';

        return redirect($fallback)->with('warning', $message);
    }

    private function resolveIndex(Request $request, string $type): ?int
    {
        return match ($type) {
            'modulo'   => (int) $request->route('modulo'),
            'minuto'   => (int) $request->route('minuto'),
            'pergunta' => (int) $request->route('diaria'),
            default    => null,
        };
    }
}
