from ..extensions import db
from datetime import datetime


class Rate(db.Model):
    __tablename__ = 'rates'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(120), nullable=False)
    tariff_type = db.Column(db.String(50), nullable=False)
    energy_prices = db.Column(db.JSON, nullable=False)  # Assuming JSON support in DB
    power_prices = db.Column(db.JSON, nullable=False)   # Assuming JSON support in DB
    valid_from = db.Column(db.Date, nullable=False)
    valid_until = db.Column(db.Date, nullable=True)
    notes = db.Column(db.Text, nullable=True)
    supplier = db.Column(db.String(120), nullable=True)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    def __repr__(self):
        return f'<Rate {self.name} ({self.tariff_type})>'

    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'tariff_type': self.tariff_type,
            'energy_prices': self.energy_prices,
            'power_prices': self.power_prices,
            'valid_from': self.valid_from.isoformat() if self.valid_from else None,
            'valid_until': self.valid_until.isoformat() if self.valid_until else None,
            'notes': self.notes,
            'supplier': self.supplier,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
