# -*- coding: utf-8 -*-

from odoo import models, fields, api


class SkeenTipoCambio(models.Model):
    _name = 'skeen.tipo.cambio'
    _description = 'Tipo de Cambio USD/MXN'
    _order = 'date desc, id desc'
    _rec_name = 'rate'

    date = fields.Date(string='Fecha', required=True, default=fields.Date.today, index=True)
    rate = fields.Float(string='Tipo de Cambio (MXN por 1 USD)', required=True, digits=(12, 4))
    source = fields.Char(string='Fuente', default='manual', help='manual, banxico, dof, etc.')
    notes = fields.Char(string='Notas')

    _sql_constraints = [
        ('date_unique', 'unique(date)', 'Ya existe un tipo de cambio registrado para esa fecha.'),
        ('rate_positive', 'CHECK(rate > 0)', 'El tipo de cambio debe ser mayor a cero.'),
    ]

    @api.model
    def get_current_rate(self):
        rec = self.search([], order='date desc, id desc', limit=1)
        return rec.rate if rec else 0.0
