from odoo import models, fields


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

    fusion_service_code = fields.Char(
        string='Service Code',
        copy=False,
        help='Carrier service code selected during shipping method selection',
    )
    # Per-package dimensions & service info (replaces single-dim fields).
    fusion_package_ids = fields.One2many(
        'fusion.order.package',
        'sale_order_id',
        string='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_package_length = fields.Float(
        string='Package Length', copy=False)
    fusion_package_width = fields.Float(
        string='Package Width', copy=False)
    fusion_package_height = fields.Float(
        string='Package Height', copy=False)

    fusion_shipment_ids = fields.One2many(
        'fusion.shipment',
        'sale_order_id',
        string='Shipments',
    )
    fusion_shipment_count = fields.Integer(
        string='Shipments',
        compute='_compute_fusion_shipment_count',
    )

    partner_ups_carrier_account = fields.Char(
        related='partner_id.property_ups_carrier_account',
        string="UPS Carrier Account",
        readonly=False,
    )
    ups_bill_my_account = fields.Boolean(
        related='carrier_id.ups_bill_my_account',
        string="UPS Bill My Account",
    )

    def _compute_fusion_shipment_count(self):
        for order in self:
            order.fusion_shipment_count = len(
                order.fusion_shipment_ids)

    def action_view_fusion_shipments(self):
        self.ensure_one()
        shipments = self.env['fusion.shipment'].search(
            [('sale_order_id', '=', self.id)]
        )
        action = {
            'type': 'ir.actions.act_window',
            'name': 'Shipments',
            'res_model': 'fusion.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
