"""Models for Favorites system with SQLModel support"""
import uuid
import json
from typing import Optional, Dict, List
from datetime import datetime
from sqlmodel import SQLModel, Field, Column, String

class FavoriteBase(SQLModel):
    """Base schema for favorite anime"""
    anime_id: str = Field(index=True)
    title: str = Field(index=True)
    url: str
    provider: str
    poster_url: Optional[str] = None
    
    # Timestamps
    created_at: datetime = Field(default_factory=datetime.now)
    updated_at: datetime = Field(default_factory=datetime.now)

class FavoriteTable(FavoriteBase, table=True):
    """Database table for favorites"""
    __tablename__ = "favorites"
    
    id: str = Field(
        default_factory=lambda: str(uuid.uuid4()),
        primary_key=True,
        index=True,
        nullable=False
    )
    user_id: str = Field(foreign_key="users.id", index=True, default="default")
    
    # Store metadata dictionary as JSON string in SQLite
    metadata_json: Optional[str] = Field(default="{}", sa_column=Column(String))
    
    @property
    def anime_metadata(self) -> Dict:
        try:
            return json.loads(self.metadata_json or "{}")
        except json.JSONDecodeError:
            return {}
    
    @anime_metadata.setter
    def anime_metadata(self, value: Dict):
        self.metadata_json = json.dumps(value or {})
