<?php

declare(strict_types=1);

namespace ImovelZapAi\SuperAdmin\Infrastructure\Http\Controllers\Web;

use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use ImovelZapAi\SuperAdmin\Application\Actions\ManageIncidentAction;
use ImovelZapAi\SuperAdmin\Domain\Enums\PlatformIncidentSeverity;
use ImovelZapAi\SuperAdmin\Domain\Enums\PlatformIncidentStatus;
use ImovelZapAi\SuperAdmin\Infrastructure\Persistence\Eloquent\PlatformIncidentModel;

final class PlatformIncidentController
{
    public function index(): View
    {
        return view('super-admin.incidents.index', [
            'incidents' => PlatformIncidentModel::query()->orderByDesc('created_at')->paginate(30),
        ]);
    }

    public function store(Request $request, ManageIncidentAction $action): RedirectResponse
    {
        $data = $request->validate([
            'title' => ['required', 'string', 'max:200'],
            'description' => ['nullable', 'string'],
            'severity' => ['required', 'string'],
            'affected_tenant_ids' => ['nullable', 'string'],
        ]);

        $severity = PlatformIncidentSeverity::tryFrom($data['severity']) ?? PlatformIncidentSeverity::Medium;
        $ids = array_values(array_filter(array_map('trim', explode(',', (string) ($data['affected_tenant_ids'] ?? '')))));

        $action->open($data['title'], $data['description'] ?? null, $severity, $ids ?: null);

        return back()->with('status', 'Incidente aberto.');
    }

    public function updateStatus(Request $request, string $incident, ManageIncidentAction $action): RedirectResponse
    {
        $data = $request->validate([
            'status' => ['required', 'string'],
        ]);
        $status = PlatformIncidentStatus::tryFrom($data['status']);
        if ($status === null) {
            return back()->withErrors(['status' => 'Status inválido.']);
        }

        $action->updateStatus($incident, $status);

        return back()->with('status', 'Status do incidente atualizado.');
    }
}
