"""Add milestones table and milestone_id to notes."""

from alembic import op

revision = "0020"
down_revision = "0019"


def upgrade() -> None:
    op.execute("""
        CREATE TABLE IF NOT EXISTS milestones (
            id          SERIAL PRIMARY KEY,
            user_id     INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
            project_id  INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
            title       TEXT NOT NULL DEFAULT '',
            description TEXT,
            status      TEXT NOT NULL DEFAULT 'active',
            order_index INTEGER NOT NULL DEFAULT 0,
            created_at  TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
            updated_at  TIMESTAMP WITH TIME ZONE DEFAULT NOW()
        )
    """)
    op.execute("CREATE INDEX IF NOT EXISTS ix_milestones_user_id ON milestones(user_id)")
    op.execute("CREATE INDEX IF NOT EXISTS ix_milestones_project_id ON milestones(project_id)")

    op.execute("""
        ALTER TABLE notes
        ADD COLUMN IF NOT EXISTS milestone_id INTEGER REFERENCES milestones(id) ON DELETE SET NULL
    """)
    op.execute("CREATE INDEX IF NOT EXISTS ix_notes_milestone_id ON notes(milestone_id)")


def downgrade() -> None:
    op.execute("DROP INDEX IF EXISTS ix_notes_milestone_id")
    op.execute("ALTER TABLE notes DROP COLUMN IF EXISTS milestone_id")
    op.execute("DROP INDEX IF EXISTS ix_milestones_project_id")
    op.execute("DROP INDEX IF EXISTS ix_milestones_user_id")
    op.execute("DROP TABLE IF EXISTS milestones")
