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

from odoo import models, fields, api, _
import logging

_logger = logging.getLogger(__name__)


class FusionLoanerHistory(models.Model):
    """Audit trail for loaner equipment actions."""
    _name = 'fusion.loaner.history'
    _description = 'Loaner History Log'
    _order = 'action_date desc, id desc'

    # =========================================================================
    # REFERENCE FIELDS
    # =========================================================================
    
    checkout_id = fields.Many2one(
        'fusion.loaner.checkout',
        string='Checkout Record',
        ondelete='cascade',
        required=True,
    )
    lot_id = fields.Many2one(
        'stock.lot',
        string='Serial Number',
        help='The serial number this action relates to',
    )
    product_id = fields.Many2one(
        'product.product',
        string='Product',
        related='checkout_id.product_id',
        store=True,
    )
    partner_id = fields.Many2one(
        'res.partner',
        string='Client',
        related='checkout_id.partner_id',
        store=True,
    )

    # =========================================================================
    # ACTION DETAILS
    # =========================================================================
    
    action = fields.Selection([
        ('create', 'Created'),
        ('checkout', 'Checked Out'),
        ('return', 'Returned'),
        ('condition_update', 'Condition Updated'),
        ('reminder_sent', 'Reminder Sent'),
        ('overdue', 'Marked Overdue'),
        ('rental_pending', 'Rental Conversion Pending'),
        ('rental_converted', 'Converted to Rental'),
        ('lost', 'Marked as Lost'),
        ('note', 'Note Added'),
    ], string='Action', required=True)
    
    action_date = fields.Datetime(
        string='Date/Time',
        default=fields.Datetime.now,
        required=True,
    )
    user_id = fields.Many2one(
        'res.users',
        string='User',
        default=lambda self: self.env.user,
        required=True,
    )
    notes = fields.Text(
        string='Notes',
    )

    # =========================================================================
    # DISPLAY
    # =========================================================================
    
    def _get_action_label(self):
        """Get human-readable action label."""
        action_labels = dict(self._fields['action'].selection)
        return action_labels.get(self.action, self.action)

    def name_get(self):
        result = []
        for record in self:
            name = f"{record.checkout_id.name} - {record._get_action_label()}"
            result.append((record.id, name))
        return result

    # =========================================================================
    # SEARCH BY SERIAL
    # =========================================================================
    
    @api.model
    def get_history_by_serial(self, lot_id):
        """Get all history for a specific serial number."""
        return self.search([('lot_id', '=', lot_id)], order='action_date desc')

    @api.model
    def get_history_by_product(self, product_id):
        """Get all history for a specific product."""
        return self.search([('product_id', '=', product_id)], order='action_date desc')
