"""v0.3 — contributions table

Adds contribution tracking: bug reports, feature requests, extension-point
proposals, and upstream PRs, each as a typed artifact with status lifecycle.

Revision ID: c2d3e4f5a6b7
Revises: b1c2d3e4f5a6
Create Date: 2026-02-28 00:00:00.000000
"""
from typing import Sequence, Union

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

revision: str = "c2d3e4f5a6b7"
down_revision: Union[str, None] = "b1c2d3e4f5a6"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    contributiontype = postgresql.ENUM(
        "br", "fr", "ep", "upr",
        name="contributiontype", create_type=True,
    )
    contributionstatus = postgresql.ENUM(
        "draft", "submitted", "acknowledged", "accepted",
        "rejected", "merged", "withdrawn",
        name="contributionstatus", create_type=True,
    )

    op.create_table(
        "contributions",
        sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True,
                  server_default=sa.text("gen_random_uuid()")),
        sa.Column("type", contributiontype, nullable=False),
        sa.Column("target_org", sa.String(200), nullable=True),
        sa.Column("target_repo", sa.String(200), nullable=True),
        sa.Column("slug", sa.String(200), nullable=True),
        sa.Column("title", sa.String(500), nullable=False),
        sa.Column("status", contributionstatus, nullable=False,
                  server_default="draft"),
        sa.Column("body_path", sa.Text, nullable=True),
        sa.Column("related_topic_id", postgresql.UUID(as_uuid=True),
                  sa.ForeignKey("topics.id", ondelete="SET NULL"), nullable=True),
        sa.Column("related_workstream_id", postgresql.UUID(as_uuid=True),
                  sa.ForeignKey("workstreams.id", ondelete="SET NULL"), nullable=True),
        sa.Column("submitted_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column("resolved_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column("notes", sa.Text, nullable=True),
        sa.Column("created_at", sa.DateTime(timezone=True),
                  server_default=sa.text("now()"), nullable=False),
        sa.Column("updated_at", sa.DateTime(timezone=True),
                  server_default=sa.text("now()"), nullable=False),
    )
    op.create_index("ix_contributions_type", "contributions", ["type"])
    op.create_index("ix_contributions_status", "contributions", ["status"])
    op.create_index("ix_contributions_target_repo", "contributions",
                    ["target_org", "target_repo"])


def downgrade() -> None:
    op.drop_table("contributions")
    op.execute("DROP TYPE IF EXISTS contributionstatus")
    op.execute("DROP TYPE IF EXISTS contributiontype")
