package cn.yunzhixue.ability.center.examsprint.infrastructure.report.storage;

import cn.yunzhixue.ability.center.examsprint.domain.report.ExamSprintReportStorage.StoredExamSprintReportContent;
import cn.yunzhixue.ability.center.examsprint.domain.report.ExamSprintReportStorage.StoredExamSprintReportFile;
import cn.yunzhixue.ability.center.examsprint.domain.report.ReportType;
import org.junit.jupiter.api.Test;

import java.net.URI;
import java.time.Duration;
import java.time.Instant;

import static org.assertj.core.api.Assertions.assertThat;

class InMemoryExamSprintReportStorageTest {

    /**
     * 上传中文新文件名后生成下载 URL 时，应使用上传时的 reportId 而不是从文件名前缀解析。
     */
    @Test
    void generateDownloadUrlUsesUploadedReportIdForLocalizedFileName() {
        InMemoryExamSprintReportStorage storage = new InMemoryExamSprintReportStorage();
        StoredExamSprintReportFile file = storage.upload(
                "report-001",
                ReportType.OUTLOOK,
                "冯亿豪-临考词汇突击潜力展望报告-20260102080000.pdf",
                new byte[]{1, 2, 3},
                Instant.parse("2026-01-02T08:05:00Z"));

        URI downloadUrl = storage.generateDownloadUrl(file.storageObjectKey(), Duration.ofMinutes(5));

        assertThat(downloadUrl).isEqualTo(URI.create("/api/exam-sprint/reports/report-001/download"));
    }

    /**
     * 下载已上传的中文新文件名文件时，应返回原始文件名、PDF content type，并对 bytes 做防御性拷贝。
     */
    @Test
    void downloadReturnsLocalizedFileNamePdfContentTypeAndClonedBytes() {
        InMemoryExamSprintReportStorage storage = new InMemoryExamSprintReportStorage();
        byte[] uploadedBytes = new byte[]{1, 2, 3};
        StoredExamSprintReportFile file = storage.upload(
                "report-001",
                ReportType.OUTLOOK,
                "冯亿豪-临考词汇突击潜力展望报告-20260102080000.pdf",
                uploadedBytes,
                Instant.parse("2026-01-02T08:05:00Z"));
        uploadedBytes[0] = 9;

        StoredExamSprintReportContent content = storage.download(file.storageObjectKey()).orElseThrow();

        assertThat(content.fileName()).isEqualTo("冯亿豪-临考词汇突击潜力展望报告-20260102080000.pdf");
        assertThat(content.bytes()).containsExactly(1, 2, 3).isNotSameAs(uploadedBytes);
        assertThat(content.contentType()).isEqualTo("application/pdf");

        content.bytes()[0] = 7;
        assertThat(storage.download(file.storageObjectKey()).orElseThrow().bytes()).containsExactly(1, 2, 3);
    }
}
