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

from odoo import models, fields, api, _
from odoo.exceptions import UserError


class FusionApiKey(models.Model):
    _name = 'fusion.api.key'
    _description = 'API Key'
    _order = 'provider_id, is_default desc, name'

    provider_id = fields.Many2one(
        'fusion.api.provider', required=True, ondelete='cascade',
    )
    provider_type = fields.Selection(
        related='provider_id.provider_type', store=True, readonly=True,
    )
    name = fields.Char(required=True, string='Label')

    api_key = fields.Char(string='API Key', groups='fusion_api.group_admin')

    client_id = fields.Char(groups='fusion_api.group_admin')
    client_secret = fields.Char(groups='fusion_api.group_admin')
    access_token = fields.Char(groups='fusion_api.group_admin')
    refresh_token = fields.Char(groups='fusion_api.group_admin')
    token_expiry = fields.Datetime()
    redirect_uri = fields.Char()

    environment = fields.Selection([
        ('production', 'Production'),
        ('sandbox', 'Sandbox'),
    ], default='production', required=True)
    is_active = fields.Boolean(default=True)
    is_default = fields.Boolean(default=False)
    last_validated_at = fields.Datetime(readonly=True)
    validation_status = fields.Selection([
        ('unknown', 'Not Validated'),
        ('valid', 'Valid'),
        ('invalid', 'Invalid'),
    ], default='unknown', readonly=True)
    notes = fields.Text()

    masked_key = fields.Char(compute='_compute_masked_key')

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

    @api.depends('api_key')
    def _compute_masked_key(self):
        for rec in self:
            key = rec.api_key
            if key and len(key) > 8:
                rec.masked_key = key[:4] + '*' * (len(key) - 8) + key[-4:]
            elif key:
                rec.masked_key = '****'
            else:
                rec.masked_key = ''

    @api.constrains('is_default', 'provider_id', 'environment')
    def _check_single_default(self):
        for rec in self:
            if rec.is_default:
                duplicates = self.search([
                    ('provider_id', '=', rec.provider_id.id),
                    ('environment', '=', rec.environment),
                    ('is_default', '=', True),
                    ('id', '!=', rec.id),
                ])
                if duplicates:
                    raise UserError(_(
                        "Only one default key per provider per environment. "
                        "Key '%(other)s' is already the default.",
                        other=duplicates[0].name,
                    ))

    def action_validate(self):
        self.ensure_one()
        try:
            self.env['fusion.api.service']._validate_key(self)
            self.write({
                'last_validated_at': fields.Datetime.now(),
                'validation_status': 'valid',
            })
            return {
                'type': 'ir.actions.client',
                'tag': 'display_notification',
                'params': {
                    'title': _('Validation Successful'),
                    'message': _('API key is valid and working.'),
                    'type': 'success',
                    'sticky': False,
                },
            }
        except UserError as e:
            self.write({'validation_status': 'invalid'})
            raise

    def write(self, vals):
        if 'api_key' in vals and not vals['api_key']:
            for rec in self:
                if rec.api_key:
                    vals.pop('api_key')
                    break
        return super().write(vals)
