# -*- 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
import logging

_logger = logging.getLogger(__name__)


class LoanerReturnWizard(models.TransientModel):
    """Wizard to return loaner equipment."""
    _name = 'fusion.loaner.return.wizard'
    _description = 'Loaner Return Wizard'

    # =========================================================================
    # CHECKOUT REFERENCE
    # =========================================================================
    
    checkout_id = fields.Many2one(
        'fusion.loaner.checkout',
        string='Checkout Record',
        required=True,
        readonly=True,
    )
    
    # Display fields
    product_id = fields.Many2one(
        'product.product',
        string='Product',
        related='checkout_id.product_id',
        readonly=True,
    )
    lot_id = fields.Many2one(
        'stock.lot',
        string='Serial Number',
        related='checkout_id.lot_id',
        readonly=True,
    )
    partner_id = fields.Many2one(
        'res.partner',
        string='Client',
        related='checkout_id.partner_id',
        readonly=True,
    )
    checkout_date = fields.Date(
        string='Checkout Date',
        related='checkout_id.checkout_date',
        readonly=True,
    )
    days_out = fields.Integer(
        string='Days Out',
        related='checkout_id.days_out',
        readonly=True,
    )
    checkout_condition = fields.Selection(
        related='checkout_id.checkout_condition',
        readonly=True,
    )

    # =========================================================================
    # RETURN DETAILS
    # =========================================================================
    
    return_date = fields.Date(
        string='Return Date',
        required=True,
        default=fields.Date.context_today,
    )
    return_condition = fields.Selection([
        ('excellent', 'Excellent'),
        ('good', 'Good'),
        ('fair', 'Fair'),
        ('needs_repair', 'Needs Repair'),
        ('damaged', 'Damaged'),
    ], string='Condition', required=True)
    return_notes = fields.Text(
        string='Notes',
        help='Any notes about the return condition or issues',
    )
    return_photo_ids = fields.Many2many(
        'ir.attachment',
        'loaner_return_wizard_photo_rel',
        'wizard_id',
        'attachment_id',
        string='Photos',
    )

    # =========================================================================
    # DEFAULT GET
    # =========================================================================
    
    @api.model
    def default_get(self, fields_list):
        res = super().default_get(fields_list)
        
        checkout_id = self._context.get('default_checkout_id')
        if checkout_id:
            checkout = self.env['fusion.loaner.checkout'].browse(checkout_id)
            res['checkout_id'] = checkout.id
            # Default return condition to checkout condition
            res['return_condition'] = checkout.checkout_condition
        
        return res

    # =========================================================================
    # ACTION
    # =========================================================================
    
    def action_return(self):
        """Process the loaner return."""
        self.ensure_one()
        
        if not self.checkout_id:
            raise UserError(_("No checkout record found."))
        
        if self.checkout_id.state not in ('checked_out', 'overdue', 'rental_pending'):
            raise UserError(_("This loaner has already been returned or is not in a returnable state."))
        
        # Create persistent attachments for photos
        photo_ids = []
        for photo in self.return_photo_ids:
            new_attachment = self.env['ir.attachment'].create({
                'name': photo.name,
                'datas': photo.datas,
                'res_model': 'fusion.loaner.checkout',
                'res_id': self.checkout_id.id,
            })
            photo_ids.append(new_attachment.id)
        
        # Process return
        self.checkout_id.action_process_return(
            return_condition=self.return_condition,
            return_notes=self.return_notes,
            return_photos=photo_ids if photo_ids else None,
        )
        
        return {'type': 'ir.actions.act_window_close'}
