from datetime import datetime

from sqlalchemy import Boolean, Column, DateTime, ForeignKey, Integer, String, Text
from sqlalchemy.orm import relationship

from ..core.database import InternalBase


class RolAdmin(InternalBase):
    __tablename__ = "roles_admin"

    id_rol = Column(Integer, primary_key=True, index=True)
    nombre = Column(String(50), unique=True, nullable=False)

    usuarios = relationship("UsuarioAdmin", back_populates="rol")


class UsuarioAdmin(InternalBase):
    __tablename__ = "usuarios_admin"

    id_usuario = Column(Integer, primary_key=True, index=True)
    username = Column(String(100), unique=True, nullable=False, index=True)
    email = Column(String(150), unique=True, nullable=False)
    password_hash = Column(Text, nullable=False)
    nombre = Column(String(100))
    activo = Column(Boolean, default=True)
    ultimo_login = Column(DateTime, nullable=True)
    fecha_creacion = Column(DateTime, default=datetime.utcnow)
    id_rol = Column(Integer, ForeignKey("roles_admin.id_rol"), nullable=False)

    rol = relationship("RolAdmin", back_populates="usuarios")
    sesiones = relationship("SesionAdmin", back_populates="usuario", cascade="all, delete-orphan")
    logs = relationship("LogAdmin", back_populates="usuario")


class SesionAdmin(InternalBase):
    __tablename__ = "sesiones_admin"

    id_sesion = Column(Integer, primary_key=True, index=True)
    id_usuario = Column(Integer, ForeignKey("usuarios_admin.id_usuario", ondelete="CASCADE"), nullable=False)
    token = Column(Text, nullable=False, index=True)
    ip = Column(String(100), nullable=True)
    user_agent = Column(Text, nullable=True)
    fecha_inicio = Column(DateTime, default=datetime.utcnow)
    fecha_expiracion = Column(DateTime, nullable=True)

    usuario = relationship("UsuarioAdmin", back_populates="sesiones")


class LogAdmin(InternalBase):
    __tablename__ = "logs_admin"

    id_log = Column(Integer, primary_key=True, index=True)
    id_usuario = Column(Integer, ForeignKey("usuarios_admin.id_usuario", ondelete="SET NULL"), nullable=True)
    accion = Column(String(255))
    descripcion = Column(Text, nullable=True)
    fecha = Column(DateTime, default=datetime.utcnow)

    usuario = relationship("UsuarioAdmin", back_populates="logs")
