<?php
declare(strict_types=1);

final class TicketCommentRepository {
    public static function listForTicket(int $ticketId): array {
        // Do not call TicketRepository::getById here — mapDetailRow already loads comments.
        $pdo = Database::pdo();
        $stmt = $pdo->prepare(
            'SELECT id, ticket_id, author_username, body, created_at_ms, updated_at_ms
             FROM ticket_comments WHERE ticket_id = ? ORDER BY created_at_ms ASC, id ASC'
        );
        $stmt->execute([$ticketId]);
        $out = [];
        foreach ($stmt->fetchAll() as $row) {
            $out[] = [
                'id' => (int) $row['id'],
                'ticket_id' => (int) $row['ticket_id'],
                'author_username' => (string) $row['author_username'],
                'body' => (string) $row['body'],
                'created_at_ms' => (int) $row['created_at_ms'],
                'updated_at_ms' => (int) $row['updated_at_ms'],
            ];
        }
        return $out;
    }

    public static function add(int $ticketId, string $author, string $body): array {
        $ticket = TicketRepository::getById($ticketId);
        if (!$ticket) {
            throw new RuntimeException('not found');
        }
        $body = trim($body);
        if ($body === '') {
            throw new InvalidArgumentException('comment body required');
        }
        $author = mb_substr(trim($author), 0, 64);
        if ($author === '') {
            throw new InvalidArgumentException('author required');
        }
        $now = (int) round(microtime(true) * 1000);
        $pdo = Database::pdo();
        $stmt = $pdo->prepare(
            'INSERT INTO ticket_comments (ticket_id, author_username, body, created_at_ms, updated_at_ms)
             VALUES (?, ?, ?, ?, ?)'
        );
        $stmt->execute([$ticketId, $author, $body, $now, $now]);
        $id = (int) $pdo->lastInsertId();
        $pdo->prepare('UPDATE tickets SET updated_at_ms = ? WHERE id = ?')->execute([$now, $ticketId]);
        return [
            'id' => $id,
            'ticket_id' => $ticketId,
            'author_username' => $author,
            'body' => $body,
            'created_at_ms' => $now,
            'updated_at_ms' => $now,
        ];
    }
}
