# -*- coding: utf-8 -*-
# Copyright 2024-2026 Nexa Systems Inc.
# License OPL-1 (Odoo Proprietary License v1.0)

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


class LTCRepairCreateSOWizard(models.TransientModel):
    _name = 'fusion.ltc.repair.create.so.wizard'
    _description = 'LTC Repair - Link Contact & Create Sale Order'

    repair_id = fields.Many2one(
        'fusion.ltc.repair',
        string='Repair Request',
        required=True,
        readonly=True,
    )
    client_name = fields.Char(
        string='Client Name',
        readonly=True,
    )
    action_type = fields.Selection([
        ('create_new', 'Create New Contact'),
        ('link_existing', 'Link to Existing Contact'),
    ], string='Action', default='create_new', required=True)
    partner_id = fields.Many2one(
        'res.partner',
        string='Existing Contact',
    )

    def action_confirm(self):
        self.ensure_one()
        repair = self.repair_id

        if self.action_type == 'create_new':
            if not self.client_name:
                raise UserError(_('Client name is required to create a new contact.'))
            partner = self.env['res.partner'].create({
                'name': self.client_name,
            })
            repair.client_id = partner
        elif self.action_type == 'link_existing':
            if not self.partner_id:
                raise UserError(_('Please select an existing contact.'))
            repair.client_id = self.partner_id

        return repair._create_linked_sale_order()
