from __future__ import annotations

"""Invoice row mapper for API formatting and metadata enrichment."""


from typing import Any


def map_invoice_row(service: Any, r: dict[str, Any]) -> dict[str, Any]:
    """Maps database row into serialized invoice dict with enriched metadata."""
    item_dict = dict(r)
    item_dict["id"] = str(item_dict["id"])
    if item_dict.get("matched_project_id"):
        item_dict["matched_project_id"] = str(item_dict["matched_project_id"])
    if item_dict.get("issue_date"):
        item_dict["issue_date"] = str(item_dict["issue_date"])
    if item_dict.get("signed_at"):
        item_dict["signed_at"] = str(item_dict["signed_at"])
    if item_dict.get("created_at"):
        item_dict["created_at"] = str(item_dict["created_at"])
    if item_dict.get("payment_due_date"):
        item_dict["payment_due_date"] = str(item_dict["payment_due_date"])
        
    for num_col in (
        "subtotal_amount_vnd",
        "vat_rate_percent",
        "vat_amount_vnd",
        "total_amount_vnd",
        "remaining_amount_vnd",
    ):
        if num_col in item_dict and item_dict[num_col] is not None:
            item_dict[num_col] = float(item_dict[num_col])
    item_dict["is_cash_register"] = service.is_cash_register_invoice(
        item_dict.get("invoice_series"), str(item_dict.get("template_code", ""))
    )
    item_dict["invoice_type_info"] = service.get_invoice_type_metadata(
        item_dict.get("invoice_series"),
        str(item_dict.get("template_code", "")),
        item_dict.get("seller_name"),
    )
    item_dict["category_info"] = service.infer_invoice_category(
        item_dict.get("seller_name", ""),
        item_dict.get("notes", ""),
        item_dict.get("item_names_summary", ""),
    )
    return item_dict
