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

import logging
from datetime import timedelta
from odoo import models, fields, api

_logger = logging.getLogger(__name__)


class FusionInventoryBooking(models.Model):
    _name = 'fusion.inventory.booking'
    _description = 'Inventory Product Booking'
    _order = 'create_date desc'
    _rec_name = 'display_name'

    product_id = fields.Many2one(
        'product.product', string='Product',
        required=True, ondelete='cascade', index=True)
    product_tmpl_id = fields.Many2one(
        related='product_id.product_tmpl_id', store=True)
    user_id = fields.Many2one(
        'res.users', string='Booked By',
        required=True, default=lambda self: self.env.uid, index=True)
    quantity = fields.Float(string='Quantity', default=1.0, required=True)
    expiry_datetime = fields.Datetime(
        string='Expires At', required=True,
        default=lambda self: fields.Datetime.now() + timedelta(hours=24))
    state = fields.Selection([
        ('active', 'Active'),
        ('expired', 'Expired'),
        ('released', 'Released'),
    ], string='Status', default='active', required=True, index=True)
    notes = fields.Text(string='Notes')

    display_name = fields.Char(compute='_compute_display_name')

    @api.depends('product_id', 'user_id', 'state')
    def _compute_display_name(self):
        for rec in self:
            rec.display_name = f'{rec.product_id.name} - {rec.user_id.name} ({rec.state})'

    @api.model
    def create(self, vals):
        if 'expiry_datetime' not in vals:
            hold_hours = int(self.env['ir.config_parameter'].sudo().get_param(
                'fusion_inventory.booking_hold_hours', '24') or 24)
            vals['expiry_datetime'] = fields.Datetime.now() + timedelta(hours=hold_hours)
        return super().create(vals)

    def action_release(self):
        self.write({'state': 'released'})

    @api.model
    def _cron_expire_bookings(self):
        expired = self.search([
            ('state', '=', 'active'),
            ('expiry_datetime', '<', fields.Datetime.now()),
        ])
        if expired:
            expired.write({'state': 'expired'})
            _logger.info('Expired %d inventory bookings', len(expired))

    @api.model
    def get_booked_qty(self, product_id):
        bookings = self.search([
            ('product_id', '=', product_id),
            ('state', '=', 'active'),
        ])
        return sum(bookings.mapped('quantity'))
