from __future__ import annotations

from datetime import datetime
from typing import Optional
import uuid

from sqlalchemy import Column, DateTime, Text
from sqlmodel import Field

from fmatch.saas.db import Base


class SalesforceAIReport(Base, table=True):
    """Persisted AI-generated SOQL report definitions for reuse and scheduling."""

    __tablename__ = "salesforce_ai_reports"
    __table_args__ = {"extend_existing": True}

    id: str = Field(default_factory=lambda: str(uuid.uuid4()), primary_key=True)
    account_id: str = Field(index=True)
    user_id: str = Field(index=True)
    name: str = Field(max_length=160)
    description: Optional[str] = Field(default=None, sa_column=Column(Text))
    primary_object: str = Field(index=True)
    plan_json: str = Field(sa_column=Column(Text))
    compiled_soql: str = Field(sa_column=Column(Text))
    plan_hash: str = Field(index=True)
    scopes_json: str = Field(default="[]", sa_column=Column(Text))
    schedule_json: Optional[str] = Field(default=None, sa_column=Column(Text))
    last_run_json: Optional[str] = Field(default=None, sa_column=Column(Text))
    tier: Optional[str] = Field(default=None, index=True)
    version: int = Field(default=1)
    created_at: datetime = Field(default_factory=datetime.utcnow, index=True)
    updated_at: datetime = Field(
        default_factory=datetime.utcnow,
        sa_column=Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow),
    )
    archived_at: Optional[datetime] = Field(
        default=None,
        sa_column=Column(DateTime, nullable=True, index=True),
    )
