<?php

declare(strict_types=1);

namespace App\Repositories;

final class ReportDeliveryRepository extends BaseRepository
{
    public function create(array $data): array
    {
        if ($this->pdo) {
            $statement = $this->pdo->prepare(
                'INSERT INTO report_deliveries
                    (report_id, channel, recipient_name, recipient_email, subject, message_id, provider_status, delivery_status, evidence_json, sent_at, created_at)
                 VALUES
                    (:report_id, :channel, :recipient_name, :recipient_email, :subject, :message_id, :provider_status, :delivery_status, :evidence_json, :sent_at, NOW())'
            );
            $statement->execute([
                'report_id' => $data['report_id'],
                'channel' => $data['channel'],
                'recipient_name' => $data['recipient_name'] ?? null,
                'recipient_email' => $data['recipient_email'] ?? null,
                'subject' => $data['subject'],
                'message_id' => $data['message_id'] ?? null,
                'provider_status' => $data['provider_status'] ?? null,
                'delivery_status' => $data['delivery_status'],
                'evidence_json' => json_encode($data['evidence'] ?? [], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR),
                'sent_at' => $data['sent_at'] ?? date('Y-m-d H:i:s'),
            ]);

            $data['id'] = (int) $this->pdo->lastInsertId();
        }

        return $data;
    }

    public function latestForReport(int $reportId): ?array
    {
        if (!$this->pdo) {
            return null;
        }

        $statement = $this->pdo->prepare(
            'SELECT * FROM report_deliveries WHERE report_id = :report_id ORDER BY created_at DESC LIMIT 1'
        );
        $statement->execute(['report_id' => $reportId]);
        $delivery = $statement->fetch();

        return $delivery ?: null;
    }
}
