# -*- coding: utf-8 -*-

from odoo import models, fields, api, _
from odoo.exceptions import UserError


class FusionMatchSaleOrderWiz(models.TransientModel):
    _name = 'fusion.match.so.wiz'
    _description = 'Fusion - Match Sale Order Wizard'

    fusion_po_id = fields.Many2one(
        'purchase.order',
        string='Purchase Order',
        required=True,
        readonly=True,
    )
    fusion_sale_order_id = fields.Many2one(
        'sale.order',
        string='Sale Order',
        help='Select the Sale Order to link to this Purchase Order',
    )
    fusion_search_hint = fields.Char(
        string='Search Hint',
        readonly=True,
        help='Suggested search term based on Marked For field',
    )

    def action_fusion_confirm(self):
        self.ensure_one()

        if not self.fusion_sale_order_id:
            raise UserError(_("Please select a Sale Order."))

        customer = self.fusion_sale_order_id.partner_id

        self.fusion_po_id.write({
            'fusion_sale_ids': [(4, self.fusion_sale_order_id.id)],
            'fusion_marked_for_ids': [(4, customer.id)],
        })

        return {
            'type': 'ir.actions.client',
            'tag': 'display_notification',
            'params': {
                'title': _('Success'),
                'message': _('Linked Purchase Order %s to Sale Order %s') % (
                    self.fusion_po_id.name,
                    self.fusion_sale_order_id.name,
                ),
                'type': 'success',
                'sticky': False,
                'next': {'type': 'ir.actions.act_window_close'},
            },
        }
