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


class NacefFiscalPurge(models.Model):
    _inherit = "nacef.fiscal.purge"

    def _purge_orders(self):
        self.ensure_one()
        return self.env["pos.order"].search([
            ("company_id", "=", self.company_id.id),
            ("nacef_imdf", "=", self.imdf),
            ("nacef_signed", "=", True),
            ("date_order", "<", self.cutoff_date),
        ])

    def _purge_date_start(self):
        """Floor of the purge window = earliest order date (E1301 archive)."""
        self.ensure_one()
        orders = self._purge_orders()
        if orders:
            earliest = min(orders.mapped("date_order"))
            return earliest.replace(hour=0, minute=0, second=0, microsecond=0)
        return super()._purge_date_start()

    def _purge_encaissement(self):
        """Delete the sealed POS orders of the window. The audit trail and the
        closings (perpetual totals) are untouched (E1402)."""
        self.ensure_one()
        orders = self._purge_orders()
        count = len(orders)
        total = sum(orders.mapped("amount_total"))
        if orders:
            # clear Odoo's own "no delete of finalised order" guard, drop the
            # payments that reference the orders (no FK cascade), then delete
            # through the sanctioned purge context (bypasses the seal guard).
            orders.write({"state": "cancel"})
            orders.mapped("payment_ids").sudo().unlink()
            orders.with_context(nacef_purge=True).unlink()
        return count, total
