from __future__ import annotations

from io import BytesIO

from apps.core.utils.export import (
    csv_response,
    write_csv,
    write_xlsx,
    xlsx_response,
)


def test_write_csv_encodes_headers_and_rows_as_utf8():
    data = write_csv(["Code", "Name", "Value"], [["A1", "Alpha", 1], ["B1", "Béta", 2]])

    decoded = data.decode("utf-8").splitlines()
    assert decoded[0] == "Code,Name,Value"
    assert decoded[1] == "A1,Alpha,1"
    # Non-ASCII round-trips.
    assert "Béta" in decoded[2]


def test_csv_response_sets_attachment_headers():
    response = csv_response(["a"], [["1"]], filename="sample.csv")

    assert response["Content-Type"].startswith("text/csv")
    assert response["Content-Disposition"] == 'attachment; filename="sample.csv"'
    assert b"1" in response.content


def test_write_xlsx_returns_valid_openpyxl_workbook():
    from openpyxl import load_workbook

    data = write_xlsx(["H1", "H2"], [["r1c1", 1], ["r2c1", 2]], sheet_name="Results")
    wb = load_workbook(BytesIO(data))

    assert wb.active.title == "Results"
    assert [cell.value for cell in wb.active[1]] == ["H1", "H2"]
    assert wb.active["B3"].value == 2


def test_xlsx_response_sets_spreadsheet_content_type():
    response = xlsx_response(["a"], [["1"]], filename="rep.xlsx")

    assert "spreadsheetml.sheet" in response["Content-Type"]
    assert response["Content-Disposition"] == 'attachment; filename="rep.xlsx"'
