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

from odoo import models, fields, api


class FusionApiConsumer(models.Model):
    _name = 'fusion.api.consumer'
    _description = 'API Consumer (Fusion Module)'
    _order = 'name'

    name = fields.Char(required=True, string='Display Name')
    technical_name = fields.Char(required=True, index=True)
    module_id = fields.Many2one('ir.module.module', string='Odoo Module', readonly=True)
    module_state = fields.Selection(
        related='module_id.state', string='Module Status', readonly=True,
    )

    is_active = fields.Boolean(default=True, string='API Access Enabled', tracking=True)
    auto_detected = fields.Boolean(default=False, readonly=True)
    first_seen_at = fields.Datetime(readonly=True)

    access_ids = fields.One2many('fusion.api.access', 'consumer_id', string='Access Rules')

    total_month_cost = fields.Float(
        compute='_compute_usage_stats', string='Month Cost (USD)',
    )
    total_month_requests = fields.Integer(
        compute='_compute_usage_stats', string='Month Requests',
    )

    company_id = fields.Many2one('res.company', default=lambda self: self.env.company)

    _sql_constraints = [
        ('technical_name_company_uniq', 'unique(technical_name, company_id)',
         'Consumer technical name must be unique per company.'),
    ]

    def _compute_usage_stats(self):
        today = fields.Date.today()
        month_start = today.replace(day=1)
        for rec in self:
            usages = self.env['fusion.api.usage'].sudo().search([
                ('consumer_id', '=', rec.id),
                ('create_date', '>=', fields.Datetime.to_string(month_start)),
                ('status', '=', 'success'),
            ])
            rec.total_month_cost = sum(u.estimated_cost_usd for u in usages)
            rec.total_month_requests = len(usages)

    def action_toggle_access(self):
        for rec in self:
            rec.is_active = not rec.is_active
