<?php

declare(strict_types=1);

namespace App\Modules\Support\Controllers;

use App\Modules\Support\Application\SupportService;
use PDO;

class SupportController
{
    public function __construct(private readonly SupportService $supportService)
    {
    }

    /**
     * @return array<string, mixed>
     */
    public function index(PDO $pdo, array $auth, array $query = []): array
    {
        $requests = $this->supportService->listForTenant($pdo, $auth);
        $requestId = trim((string) ($query['request'] ?? ''));
        $detail = $requestId !== '' ? $this->supportService->find($pdo, $auth, $requestId) : null;

        if ($detail === null && $requestId !== '') {
            $detailNotice = 'Der ausgewählte Vorgang wurde nicht gefunden oder ist nicht sichtbar.';
        } else {
            $detailNotice = null;
        }

        return [
            'title' => 'Support',
            'can_manage' => $this->supportService->canManage($auth),
            'summary' => $this->supportService->summary($pdo, $auth),
            'requests' => array_map(static fn($request): array => $request->toArray(), $requests),
            'detail' => $detail?->toArray(),
            'detail_notice' => $detailNotice,
            'categories' => $this->supportService->categories(),
            'directions' => $this->supportService->directions(),
            'statuses' => $this->supportService->statuses(),
            'priorities' => $this->supportService->priorities(),
            'route_targets' => $this->supportService->routeTargets(),
        ];
    }

    public function handlePost(PDO $pdo, array $auth, array $post, array $query = []): void
    {
        $action = (string) ($post['action'] ?? '');
        $requestId = trim((string) ($post['request_id'] ?? ''));

        if ($action === 'create-request') {
            $request = $this->supportService->create($pdo, $auth, $post);
            app_flash('Der Support-Vorgang ' . $request->requestNumber . ' wurde angelegt.', 'success');
            app_redirect('/support/?request=' . $request->id);
        }

        if ($action === 'add-message' && $requestId !== '') {
            $request = $this->supportService->addMessage($pdo, $auth, $requestId, $post);
            app_flash('Deine Nachricht wurde zum Vorgang hinzugefügt.', 'success');
            app_redirect('/support/?request=' . $request->id);
        }

        if ($action === 'update-request' && $requestId !== '') {
            $request = $this->supportService->updateRequest($pdo, $auth, $requestId, $post);
            app_flash('Der Vorgang wurde aktualisiert.', 'success');
            app_redirect('/support/?request=' . $request->id);
        }

        app_flash('Die Aktion konnte nicht verarbeitet werden.', 'error');
        app_redirect('/support/' . (isset($query['request']) && $query['request'] !== '' ? '?request=' . rawurlencode((string) $query['request']) : ''));
    }
}
