from datetime import date

import pytest
from pydantic import ValidationError

from app.api.routes.admin_imports import (
    COL_ISSUE_DATE,
    COL_COURSE_END_DATE,
    COL_COURSE_START_DATE,
    COL_NAME,
    COL_PHONE,
    COL_PROJECT,
    TEMPLATE_HEADERS,
    build_import_template_workbook,
    date_is_valid,
    parse_issue_date,
    row_errors,
)
from app.schemas.certificate import CertificateCreate


def test_parse_issue_date_accepts_common_formats():
    assert parse_issue_date("2026-06-01") == date(2026, 6, 1)
    assert parse_issue_date("2026/06/01") == date(2026, 6, 1)


def test_row_errors_require_project_code_to_exist():
    row = {
        COL_NAME: "张三",
        COL_PHONE: "13800000000",
        COL_PROJECT: "BAD",
        COL_COURSE_START_DATE: "2026-05-01",
        COL_COURSE_END_DATE: "2026-05-31",
        COL_ISSUE_DATE: "2026-06-01",
    }
    assert "Project code is inactive or missing" in row_errors(row, {"DBY"})


def test_date_is_valid_rejects_bad_text():
    assert not date_is_valid("not-a-date")


def test_row_errors_rejects_reversed_course_period():
    row = {
        COL_NAME: "张三",
        COL_PHONE: "13800000000",
        COL_PROJECT: "DBY",
        COL_COURSE_START_DATE: "2026-06-30",
        COL_COURSE_END_DATE: "2026-06-01",
        COL_ISSUE_DATE: "2026-07-05",
    }
    assert "课程结束日期不能早于课程开始日期" in row_errors(row, {"DBY"})


def test_row_errors_explains_required_date_format():
    row = {
        COL_NAME: "张三",
        COL_PHONE: "13800000000",
        COL_PROJECT: "DBY",
        COL_COURSE_START_DATE: "2026年6月1日",
        COL_COURSE_END_DATE: "2026-06-30",
        COL_ISSUE_DATE: "2026-07-05",
    }
    assert "课程开始日期格式错误，请使用YYYY-MM-DD，例如2026-06-01" in row_errors(row, {"DBY"})


def test_import_template_contains_date_examples_and_validation():
    workbook = build_import_template_workbook()
    data_sheet = workbook["证书导入模板"]
    instruction_sheet = workbook["填写说明"]

    assert [cell.value for cell in data_sheet[1]] == TEMPLATE_HEADERS
    assert data_sheet.column_dimensions["D"].number_format == "yyyy-mm-dd"
    assert len(data_sheet.data_validations.dataValidation) == 3
    assert instruction_sheet["C5"].value == "2026-06-01"
    assert "YYYY-MM-DD" in instruction_sheet["D5"].value


def test_certificate_create_rejects_reversed_course_period():
    with pytest.raises(ValidationError, match="课程结束日期不能早于课程开始日期"):
        CertificateCreate(
            learner_id=1,
            project_code="DBY",
            course_start_date="2026-06-30",
            course_end_date="2026-06-01",
            issue_date="2026-07-05",
        )


def test_certificate_create_has_no_issuer_field():
    certificate = CertificateCreate(
        learner_id=1,
        project_code="DBY",
        course_start_date="2026-06-01",
        course_end_date="2026-06-30",
        issue_date="2026-07-05",
    )

    assert "issuer_name" not in certificate.model_dump()
