<?php
declare(strict_types=1);

namespace App\Controllers\Api;

use App\Middleware\ApiToken;
use App\Middleware\TenantScope;
use App\Models\Incident;
use Core\Controller;

final class IncidentsController extends Controller
{
    public function middleware(): array
    {
        return [ApiToken::class, TenantScope::class];
    }

    private function tenantId(): int { return (int) ($_SESSION['tenant_id'] ?? 0); }
    private function userId():   int { return (int) ($_SESSION['user']['user_id'] ?? 0); }

    public function index(): void
    {
        $filters = [
            'category' => $_GET['category'] ?? null,
            'status'   => $_GET['status']   ?? null,
            'severity' => $_GET['severity'] ?? null,
            'asset_id' => $_GET['asset_id'] ?? null,
        ];
        $this->json(['data' => Incident::listForTenant($this->tenantId(), array_filter($filters))]);
    }

    public function show(int $id): void
    {
        $incident = Incident::findInTenant($this->tenantId(), $id);
        if (!$incident) $this->json(['error' => 'Not found'], 404);
        $incident['events'] = Incident::eventsFor($id);
        if (!empty($incident['details_json'])) {
            $incident['details'] = json_decode($incident['details_json'], true);
        }
        $this->json(['data' => $incident]);
    }

    public function create(): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
            $this->json(['error' => 'POST required'], 405);
        }
        $body = $this->input();
        if (empty($body['title']) || empty($body['category'])) {
            $this->json(['error' => 'title + category required'], 422);
        }
        $id = Incident::create($this->tenantId(), $this->userId(), $body);
        $this->json(['data' => Incident::findInTenant($this->tenantId(), $id)], 201);
    }

    public function update(int $id): void
    {
        if (!in_array(($_SERVER['REQUEST_METHOD'] ?? ''), ['POST','PUT','PATCH'], true)) {
            $this->json(['error' => 'POST/PUT/PATCH required'], 405);
        }
        $incident = Incident::findInTenant($this->tenantId(), $id);
        if (!$incident) $this->json(['error' => 'Not found'], 404);
        Incident::update($this->tenantId(), $this->userId(), $id, $this->input());
        $this->json(['data' => Incident::findInTenant($this->tenantId(), $id)]);
    }

    public function note(int $id): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
            $this->json(['error' => 'POST required'], 405);
        }
        $incident = Incident::findInTenant($this->tenantId(), $id);
        if (!$incident) $this->json(['error' => 'Not found'], 404);
        $body = $this->input();
        $msg = trim((string) ($body['message'] ?? ''));
        if ($msg === '') $this->json(['error' => 'message required'], 422);
        Incident::logEvent($id, $this->userId(), 'note', null, null, $msg);
        $this->json(['success' => true]);
    }

    public function types(): void
    {
        $this->json(['data' => Incident::typesForTenant($this->tenantId(), $_GET['category'] ?? null)]);
    }
}
