from odoo import models, fields


class StockPicking(models.Model):
    _inherit = 'stock.picking'

    fusion_shipment_count = fields.Integer(
        string='Shipments',
        compute='_compute_fusion_shipment_count',
    )

    def _compute_fusion_shipment_count(self):
        Shipment = self.env['fusion.shipment']
        for picking in self:
            picking.fusion_shipment_count = Shipment.search_count(
                [('picking_id', '=', picking.id)]
            )

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