"""
证书系统数据模型

定义证书模板和用户证书的数据结构
"""

from datetime import datetime
from enum import Enum
from typing import Optional
from sqlalchemy import Column, Integer, String, Text, Boolean, DateTime, ForeignKey, Enum as SQLEnum, DECIMAL, JSON
from sqlalchemy.orm import relationship

from app.models.base import Base


class CertificateType(str, Enum):
    """证书类型枚举"""
    COURSE = "course"           # 课程结业证书
    EXAM = "exam"               # 考试合格证书
    ACHIEVEMENT = "achievement"  # 成就证书


class CertificateTemplate(Base):
    """证书模板表"""
    __tablename__ = "certificate_templates"
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(100), nullable=False, comment="模板名称")
    type = Column(SQLEnum(CertificateType), nullable=False, comment="证书类型")
    background_url = Column(String(500), comment="证书背景图URL")
    template_html = Column(Text, comment="HTML模板内容")
    template_style = Column(Text, comment="CSS样式")
    is_active = Column(Boolean, default=True, comment="是否启用")
    sort_order = Column(Integer, default=0, comment="排序顺序")
    created_at = Column(DateTime, nullable=False, default=datetime.now)
    updated_at = Column(DateTime, nullable=False, default=datetime.now, onupdate=datetime.now)
    
    # 关联
    certificates = relationship("UserCertificate", back_populates="template")


class UserCertificate(Base):
    """用户证书表"""
    __tablename__ = "user_certificates"
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, comment="用户ID")
    template_id = Column(Integer, ForeignKey("certificate_templates.id"), nullable=False, comment="模板ID")
    certificate_no = Column(String(50), unique=True, nullable=False, comment="证书编号")
    title = Column(String(200), nullable=False, comment="证书标题")
    description = Column(Text, comment="证书描述")
    issued_at = Column(DateTime, default=datetime.now, comment="颁发时间")
    valid_until = Column(DateTime, comment="有效期至")
    
    # 关联信息
    course_id = Column(Integer, comment="关联课程ID")
    exam_id = Column(Integer, comment="关联考试ID")
    badge_id = Column(Integer, comment="关联奖章ID")
    
    # 成绩信息
    score = Column(DECIMAL(5, 2), comment="考试分数")
    completion_rate = Column(DECIMAL(5, 2), comment="完成率")
    
    # 生成的文件
    pdf_url = Column(String(500), comment="PDF文件URL")
    image_url = Column(String(500), comment="分享图片URL")
    
    # 元数据
    meta_data = Column(JSON, comment="扩展元数据")
    
    created_at = Column(DateTime, nullable=False, default=datetime.now)
    updated_at = Column(DateTime, nullable=False, default=datetime.now, onupdate=datetime.now)
    
    # 关联
    template = relationship("CertificateTemplate", back_populates="certificates")
    user = relationship("User", backref="certificates")
