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

from odoo import models, fields, api


class FusionApiUserLimit(models.Model):
    _name = 'fusion.api.user.limit'
    _description = 'API User Limit'
    _order = 'user_id, provider_id'
    _rec_name = 'display_name'

    user_id = fields.Many2one('res.users', required=True, ondelete='cascade')
    provider_id = fields.Many2one(
        'fusion.api.provider', required=True, ondelete='cascade',
    )

    monthly_budget_usd = fields.Float(
        string='Monthly Budget (USD)',
        help='Maximum monthly spend for this user. 0 = unlimited.',
    )
    max_rpd = fields.Integer(
        string='Max Requests/Day',
        help='Maximum requests per day. 0 = unlimited.',
    )
    is_blocked = fields.Boolean(string='Blocked', tracking=True)

    current_month_cost = fields.Float(
        compute='_compute_current_usage', string='Month Spend',
    )
    current_day_requests = fields.Integer(
        compute='_compute_current_usage', string='Today Requests',
    )

    display_name = fields.Char(compute='_compute_display_name', store=True)
    company_id = fields.Many2one('res.company', default=lambda self: self.env.company)

    _sql_constraints = [
        ('user_provider_uniq', 'unique(user_id, provider_id, company_id)',
         'Only one limit per user-provider pair per company.'),
    ]

    @api.depends('user_id.name', 'provider_id.name')
    def _compute_display_name(self):
        for rec in self:
            user = rec.user_id.name or ''
            provider = rec.provider_id.name or ''
            rec.display_name = f"{user} - {provider}"

    def _compute_current_usage(self):
        today = fields.Date.today()
        month_start = today.replace(day=1)
        for rec in self:
            month_usages = self.env['fusion.api.usage'].sudo().search([
                ('user_id', '=', rec.user_id.id),
                ('provider_id', '=', rec.provider_id.id),
                ('create_date', '>=', fields.Datetime.to_string(month_start)),
                ('status', '=', 'success'),
            ])
            day_usages = month_usages.filtered(
                lambda u: u.create_date.date() == today
            )
            rec.current_month_cost = sum(u.estimated_cost_usd for u in month_usages)
            rec.current_day_requests = len(day_usages)
