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

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


class MatchSaleOrderWizard(models.TransientModel):
    _name = 'match.sale.order.wiz'
    _description = "Match Sale Order Wizard"

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

    def action_confirm(self):
        """Link the selected Sale Order to the Purchase Order"""
        self.ensure_one()
        
        if not self.sale_order_id:
            raise UserError(_("Please select a Sale Order."))
        
        # Get the customer name for marked_for field
        customer_name = self.sale_order_id.partner_id.name or self.sale_order_id.partner_id.display_name
        
        # Update the Purchase Order
        self.purchase_order_id.write({
            'sale_ord_id': self.sale_order_id.id,
            'marked_for': customer_name,
        })
        
        return {
            'type': 'ir.actions.client',
            'tag': 'display_notification',
            'params': {
                'title': _('Success'),
                'message': _('Linked Purchase Order %s to Sale Order %s') % (
                    self.purchase_order_id.name,
                    self.sale_order_id.name
                ),
                'type': 'success',
                'sticky': False,
                'next': {'type': 'ir.actions.act_window_close'},
            }
        }
