"""Workflow repository (tenant-scoped)."""

from __future__ import annotations

import uuid

from sqlalchemy import select
from sqlalchemy.orm import Session

from legate.db.models.workflow import Workflow


def create(
    db: Session,
    *,
    workspace_id: uuid.UUID,
    name: str,
    description: str = "",
    definition_json: dict | None = None,
    trigger_type: str = "manual",
    trigger_config: dict | None = None,
    webhook_token: str | None = None,
    webhook_secret: str | None = None,
    created_by: uuid.UUID | None = None,
) -> Workflow:
    workflow = Workflow(
        workspace_id=workspace_id,
        name=name,
        description=description,
        definition_json=definition_json or {"nodes": [], "edges": []},
        trigger_type=trigger_type,
        trigger_config=trigger_config or {},
        webhook_token=webhook_token,
        webhook_secret=webhook_secret,
        created_by=created_by,
    )
    db.add(workflow)
    db.flush()
    return workflow


def get(db: Session, *, workspace_id: uuid.UUID, workflow_id: uuid.UUID) -> Workflow | None:
    return db.scalars(
        select(Workflow).where(Workflow.id == workflow_id, Workflow.workspace_id == workspace_id)
    ).first()


def get_by_webhook_token(db: Session, *, token: str) -> Workflow | None:
    return db.scalars(select(Workflow).where(Workflow.webhook_token == token)).first()


def list_for_workspace(db: Session, *, workspace_id: uuid.UUID) -> list[Workflow]:
    return list(
        db.scalars(
            select(Workflow)
            .where(Workflow.workspace_id == workspace_id)
            .order_by(Workflow.created_at.asc())
        ).all()
    )


def list_by_trigger(db: Session, *, trigger_type: str) -> list[Workflow]:
    return list(
        db.scalars(
            select(Workflow).where(
                Workflow.trigger_type == trigger_type, Workflow.is_active.is_(True)
            )
        ).all()
    )


def delete(db: Session, workflow: Workflow) -> None:
    db.delete(workflow)
    db.flush()
