from odoo import models, fields


class SaleOrder(models.Model):
    _inherit = 'sale.order'

    fusion_cp_service_code = fields.Char(
        string='CP Service Code',
        copy=False,
        help='Canada Post service code selected during shipping method selection',
    )
    # Per-package dimensions & service info (replaces single-dim fields).
    fusion_cp_package_ids = fields.One2many(
        'fusion.cp.order.package',
        'sale_order_id',
        string='CP Packages',
        copy=False,
    )

    # Legacy single-package dimension fields (kept for backward
    # compatibility with existing orders — new orders populate the
    # One2many above and fill these from the first package).
    fusion_cp_package_length = fields.Float(
        string='Package Length', copy=False)
    fusion_cp_package_width = fields.Float(
        string='Package Width', copy=False)
    fusion_cp_package_height = fields.Float(
        string='Package Height', copy=False)

    fusion_cp_shipment_ids = fields.One2many(
        'fusion.cp.shipment',
        'sale_order_id',
        string='CP Shipments',
    )
    fusion_cp_shipment_count = fields.Integer(
        string='CP Shipments',
        compute='_compute_fusion_cp_shipment_count',
    )

    def _compute_fusion_cp_shipment_count(self):
        for order in self:
            order.fusion_cp_shipment_count = len(
                order.fusion_cp_shipment_ids)

    def action_view_fusion_cp_shipments(self):
        self.ensure_one()
        shipments = self.env['fusion.cp.shipment'].search(
            [('sale_order_id', '=', self.id)]
        )
        action = {
            'type': 'ir.actions.act_window',
            'name': 'Canada Post Shipments',
            'res_model': 'fusion.cp.shipment',
            'view_mode': 'list,form',
            'domain': [('sale_order_id', '=', self.id)],
        }
        if len(shipments) == 1:
            action['view_mode'] = 'form'
            action['res_id'] = shipments.id
        return action
