"""
user.py — SQLAlchemy model untuk user.

Perubahan:
- Tambah relationship `tasks` ke TranskripsiTask (back_populates="owner").
"""

from sqlalchemy import Column, Integer, String, Boolean, DateTime
from sqlalchemy.orm import relationship
from datetime import datetime, timezone

from app.core.database import Base


def _utcnow():
    return datetime.now(timezone.utc)


class User(Base):
    __tablename__ = "users"

    id              = Column(Integer, primary_key=True, index=True)
    username        = Column(String, unique=True, index=True, nullable=False)
    email           = Column(String, unique=True, index=True, nullable=True)
    full_name       = Column(String, nullable=True)
    hashed_password = Column(String, nullable=False)
    role            = Column(String, default="user")    # "user" | "admin"
    is_active       = Column(Boolean, default=True)

    # ── OAuth columns ────────────────────────────────────────────────
    oauth_provider  = Column(String, nullable=True)     # "google" | "github" | None
    oauth_id        = Column(String, nullable=True)
    # inside class User, after `oauth_id` line
    balance = Column(Integer, default=0, nullable=False)

    # ── Relasi ke task ───────────────────────────────────────────────
    tasks           = relationship(
        "TranskripsiTask",
        back_populates="owner",
        lazy="dynamic",         # tidak auto-load semua task saat user di-query
        passive_deletes=True,   # biarkan DB yang handle ON DELETE SET NULL
    )

    created_at      = Column(DateTime(timezone=True), default=_utcnow)
    updated_at      = Column(DateTime(timezone=True), default=_utcnow, onupdate=_utcnow)

    def to_dict(self) -> dict:
        return {
            "id":             self.id,
            "username":       self.username,
            "email":          self.email,
            "full_name":      self.full_name,
            "role":           self.role,
            "is_active":      self.is_active,
            "oauth_provider": self.oauth_provider,
            "balance":        self.balance or 0,
            "created_at":     self.created_at.isoformat() if self.created_at else None,
        }