"""add_projects_schema

Revision ID: o9p0q1r2s3t4
Revises: n8o9p0q1r2s3
Create Date: 2025-12-30 14:00:00.000000

"""

from collections.abc import Sequence

import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql

# revision identifiers, used by Alembic.
revision: str = "o9p0q1r2s3t4"
down_revision: str | Sequence[str] | None = "n8o9p0q1r2s3"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None

DEFAULT_PROJECT_ID = "00000000-0000-0000-0000-000000000001"


def upgrade() -> None:
    """Add projects schema: workspace settings, projects table, project memberships, meeting project FK."""
    # Step 1: Add is_default and settings columns to workspaces
    op.add_column(
        "workspaces",
        sa.Column("is_default", sa.Boolean(), nullable=False, server_default=sa.text("false")),
        schema="noteflow",
    )
    op.add_column(
        "workspaces",
        sa.Column(
            "settings",
            postgresql.JSONB(astext_type=sa.Text()),
            nullable=False,
            server_default=sa.text("'{}'::jsonb"),
        ),
        schema="noteflow",
    )

    # Step 2: Create projects table
    op.create_table(
        "projects",
        sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),
        sa.Column(
            "workspace_id",
            postgresql.UUID(as_uuid=True),
            sa.ForeignKey("noteflow.workspaces.id", ondelete="CASCADE"),
            nullable=False,
        ),
        sa.Column("name", sa.Text(), nullable=False),
        sa.Column("slug", sa.Text(), nullable=True),
        sa.Column("description", sa.Text(), nullable=True),
        sa.Column("is_default", sa.Boolean(), nullable=False, server_default=sa.text("false")),
        sa.Column(
            "settings",
            postgresql.JSONB(astext_type=sa.Text()),
            nullable=False,
            server_default=sa.text("'{}'::jsonb"),
        ),
        sa.Column(
            "created_at",
            sa.DateTime(timezone=True),
            nullable=False,
            server_default=sa.text("now()"),
        ),
        sa.Column(
            "updated_at",
            sa.DateTime(timezone=True),
            nullable=False,
            server_default=sa.text("now()"),
        ),
        sa.Column("archived_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column(
            "metadata",
            postgresql.JSONB(astext_type=sa.Text()),
            nullable=False,
            server_default=sa.text("'{}'::jsonb"),
        ),
        schema="noteflow",
    )

    # Create index on workspace_id for efficient lookups
    op.create_index(
        "ix_projects_workspace_id",
        "projects",
        ["workspace_id"],
        schema="noteflow",
    )

    # Create unique constraint on (workspace_id, slug) for slugs within a workspace
    op.create_unique_constraint(
        "uq_projects_workspace_slug",
        "projects",
        ["workspace_id", "slug"],
        schema="noteflow",
    )

    # Create updated_at trigger for projects
    op.execute(
        """
        CREATE TRIGGER projects_updated_at_trigger
        BEFORE UPDATE ON noteflow.projects
        FOR EACH ROW
        EXECUTE FUNCTION noteflow.set_updated_at();
        """
    )

    # Step 3: Create project_memberships table
    op.create_table(
        "project_memberships",
        sa.Column(
            "project_id",
            postgresql.UUID(as_uuid=True),
            sa.ForeignKey("noteflow.projects.id", ondelete="CASCADE"),
            primary_key=True,
        ),
        sa.Column(
            "user_id",
            postgresql.UUID(as_uuid=True),
            sa.ForeignKey("noteflow.users.id", ondelete="CASCADE"),
            primary_key=True,
        ),
        sa.Column("role", sa.String(50), nullable=False, server_default=sa.text("'viewer'")),
        sa.Column(
            "joined_at",
            sa.DateTime(timezone=True),
            nullable=False,
            server_default=sa.text("now()"),
        ),
        schema="noteflow",
    )

    # Create index on user_id for efficient membership lookups
    op.create_index(
        "ix_project_memberships_user_id",
        "project_memberships",
        ["user_id"],
        schema="noteflow",
    )

    # Step 4: Add project_id column to meetings table
    op.add_column(
        "meetings",
        sa.Column(
            "project_id",
            postgresql.UUID(as_uuid=True),
            sa.ForeignKey("noteflow.projects.id", ondelete="SET NULL"),
            nullable=True,
        ),
        schema="noteflow",
    )

    # Create index on project_id for efficient filtering
    op.create_index(
        "ix_meetings_project_id",
        "meetings",
        ["project_id"],
        schema="noteflow",
    )

    # Step 5: Seed default project for each workspace
    # Insert a "General" default project for each existing workspace
    op.execute(
        """
        INSERT INTO noteflow.projects (id, workspace_id, name, slug, is_default, settings, metadata)
        SELECT
            gen_random_uuid(),
            w.id,
            'General',
            'general',
            true,
            '{}'::jsonb,
            '{}'::jsonb
        FROM noteflow.workspaces w
        WHERE NOT EXISTS (
            SELECT 1 FROM noteflow.projects p
            WHERE p.workspace_id = w.id AND p.is_default = true
        );
        """
    )


def downgrade() -> None:
    """Remove projects schema."""
    # Drop index on meetings.project_id
    op.drop_index("ix_meetings_project_id", table_name="meetings", schema="noteflow")

    # Drop project_id column from meetings
    op.drop_column("meetings", "project_id", schema="noteflow")

    # Drop project_memberships table
    op.drop_index(
        "ix_project_memberships_user_id",
        table_name="project_memberships",
        schema="noteflow",
    )
    op.drop_table("project_memberships", schema="noteflow")

    # Drop projects table (trigger is dropped automatically with table)
    op.drop_index("ix_projects_workspace_id", table_name="projects", schema="noteflow")
    op.drop_constraint("uq_projects_workspace_slug", "projects", schema="noteflow")
    op.drop_table("projects", schema="noteflow")

    # Drop workspace columns
    op.drop_column("workspaces", "settings", schema="noteflow")
    op.drop_column("workspaces", "is_default", schema="noteflow")
