<?php

namespace App\Http\Controllers;

use App\Models\Caso;
use App\Services\NotificationService;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

/**
 * Handles external approval links for clients/brokers (M6).
 * These routes are public (no auth required) — accessed via unique token.
 */
class AprobacionController extends Controller
{
    /**
     * Show the approval page for import acceptance (M6).
     * Client/Broker receives a link via WhatsApp/email to accept or reject.
     */
    public function show(string $token)
    {
        $caso = Caso::where('token_aprobacion', $token)
            ->where('token_expira_en', '>', now())
            ->with(['vehiculo', 'aseguradora'])
            ->first();

        if (! $caso) {
            return response()->view('aprobacion.expired', [], 404);
        }

        return view('aprobacion.show', [
            'caso' => $caso,
            'token' => $token,
        ]);
    }

    /**
     * Process the client's acceptance or rejection decision.
     */
    public function responder(Request $request, string $token)
    {
        $request->validate([
            'decision' => 'required|in:aceptado,rechazado',
        ]);

        $caso = Caso::where('token_aprobacion', $token)
            ->where('token_expira_en', '>', now())
            ->first();

        if (! $caso) {
            return response()->view('aprobacion.expired', [], 404);
        }

        $caso->update([
            'aprobacion_estado' => $request->decision,
        ]);

        // If rejected → set state to 'pendiente_proforma_cliente'
        if ($request->decision === 'rechazado') {
            $caso->update(['estado_actual' => 'pendiente_proforma_cliente']);
            NotificationService::notify($caso, 'importacion_rechazada', 'Cliente/Broker rechazó la importación para caso '.$caso->numero_reclamo);
        } else {
            // If accepted → proceed with purchase, notify proveedor
            NotificationService::notify($caso, 'importacion_aceptada', 'Cliente/Broker aceptó la importación para caso '.$caso->numero_reclamo);
        }

        // Invalidate the token
        $caso->update(['token_aprobacion' => null, 'token_expira_en' => null]);

        return view('aprobacion.gracias', [
            'decision' => $request->decision,
        ]);
    }

    /**
     * Generate a new approval token for a case (called internally by MesaComprasController).
     */
    public static function generarToken(Caso $caso): string
    {
        $token = Str::random(64);
        $caso->update([
            'token_aprobacion' => $token,
            'token_expira_en' => now()->addHours(48),
            'aprobacion_estado' => 'pendiente',
        ]);

        return $token;
    }
}
