# -*- coding: utf-8 -*-
from odoo import models


class NacefFiscalArchive(models.Model):
    _inherit = "nacef.fiscal.archive"

    def _collect_encaissement(self):
        """Serialize the signed POS orders of the period into open-format rows
        (E1301/E1302). Figées (read from immutable sealed orders) and horodatées;
        each row carries its inalterability hash so the archive is independently
        verifiable (E1303)."""
        self.ensure_one()
        orders = self.env["pos.order"].search([
            ("company_id", "=", self.company_id.id),
            ("nacef_imdf", "=", self.imdf),
            ("date_order", ">=", self.date_start),
            ("date_order", "<", self.date_stop),
            ("nacef_signed", "=", True),
        ], order="nacef_secure_sequence asc")
        rows = []
        for order in orders:
            rows.append({
                "pos_reference": order.pos_reference,
                "fiscal_reference": order.nacef_fiscal_reference,
                "ticket_identifier": order.nacef_ticket_identifier,
                "date_order": str(order.date_order),
                "operation_type": order.nacef_operation_type,
                "transaction_type": order.nacef_transaction_type,
                "origin_reference": order.nacef_origin_reference or "",
                "amount_total": order.amount_total,
                "amount_tax": order.amount_tax,
                "cashier": order.user_id.name or "",
                "online": order.nacef_online,
                "secure_sequence": order.nacef_secure_sequence,
                "prev_hash": order.nacef_prev_hash,
                "hash": order.nacef_hash,
                "lines": [{
                    "product": line.product_id.display_name,
                    "qty": line.qty,
                    "price_unit": line.price_unit,
                    "price_subtotal_incl": line.price_subtotal_incl,
                } for line in order.lines],
                "payments": [{
                    "method": pay.payment_method_id.name,
                    "amount": pay.amount,
                } for pay in order.payment_ids],
            })
        return rows
