"""
Fusion Accounting - EDI Import Wizard

Provides a transient model that lets users upload a UBL 2.1 or CII XML
file and create a draft invoice from its contents.

Original implementation by Nexa Systems Inc.
"""

import base64
import logging

from odoo import api, fields, models, _
from odoo.exceptions import UserError

_log = logging.getLogger(__name__)


class FusionEDIImportWizard(models.TransientModel):
    """
    File-upload wizard for importing electronic invoices in UBL 2.1 or
    UN/CEFACT CII format.
    """

    _name = "fusion.edi.import.wizard"
    _description = "Import EDI Invoice"

    xml_file = fields.Binary(
        string="XML File",
        required=True,
        help="Select a UBL 2.1 or CII XML invoice file to import.",
    )
    xml_filename = fields.Char(
        string="File Name",
    )
    move_type = fields.Selection(
        selection=[
            ("out_invoice", "Customer Invoice"),
            ("out_refund", "Customer Credit Note"),
            ("in_invoice", "Vendor Bill"),
            ("in_refund", "Vendor Credit Note"),
        ],
        string="Document Type",
        default="out_invoice",
        help=(
            "Fallback document type if the XML does not specify one. "
            "The parser may override this based on the XML content."
        ),
    )

    def action_import(self):
        """Parse the uploaded XML and create a draft invoice.

        Returns:
            dict: A window action opening the newly created invoice.
        """
        self.ensure_one()
        if not self.xml_file:
            raise UserError(_("Please select an XML file to import."))

        xml_bytes = base64.b64decode(self.xml_file)
        AccountMove = self.env["account.move"].with_context(
            default_move_type=self.move_type,
        )
        move = AccountMove.create_invoice_from_xml(xml_bytes)

        return {
            "type": "ir.actions.act_window",
            "name": _("Imported Invoice"),
            "res_model": "account.move",
            "res_id": move.id,
            "view_mode": "form",
            "target": "current",
        }
