"""add_jira_links_and_worklogs

Revision ID: b020jiraworklogs
Revises: b019composite
Create Date: 2026-02-17 16:00:00.000000

"""
from typing import Sequence, Union

import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

from alembic import op

revision: str = "b020jiraworklogs"
down_revision: Union[str, None] = "b019composite"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # ── jira_links: 100 % raw SQL to avoid all SQLAlchemy enum hooks ──
    op.execute("""
        DO $$ BEGIN
            IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'jiralinkentitytype') THEN
                CREATE TYPE jiralinkentitytype AS ENUM ('test', 'technique', 'campaign', 'evidence');
            END IF;
        END $$;

        DO $$ BEGIN
            IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'jirasyncdirection') THEN
                CREATE TYPE jirasyncdirection AS ENUM ('aegis_to_jira', 'jira_to_aegis', 'bidirectional');
            END IF;
        END $$;

        CREATE TABLE IF NOT EXISTS jira_links (
            id              UUID PRIMARY KEY,
            entity_type     jiralinkentitytype NOT NULL,
            entity_id       UUID NOT NULL,
            jira_issue_key  VARCHAR(50) NOT NULL,
            jira_issue_id   VARCHAR(50),
            jira_project_key VARCHAR(20),
            jira_status     VARCHAR(100),
            jira_priority   VARCHAR(50),
            jira_assignee   VARCHAR(255),
            jira_story_points VARCHAR(10),
            sync_direction  jirasyncdirection DEFAULT 'bidirectional',
            last_synced_at  TIMESTAMP,
            sync_metadata   JSONB DEFAULT '{}',
            created_by      UUID REFERENCES users(id),
            created_at      TIMESTAMP DEFAULT now(),
            updated_at      TIMESTAMP DEFAULT now()
        );

        CREATE INDEX IF NOT EXISTS ix_jira_links_entity_id
            ON jira_links (entity_id);
        CREATE INDEX IF NOT EXISTS ix_jira_links_issue_key
            ON jira_links (jira_issue_key);
        CREATE INDEX IF NOT EXISTS ix_jira_links_entity_type_entity_id
            ON jira_links (entity_type, entity_id);
    """)

    # ── worklogs table (no enums, straightforward) ───────────────────
    op.execute("""
        CREATE TABLE IF NOT EXISTS worklogs (
            id              UUID PRIMARY KEY,
            entity_type     VARCHAR(50) NOT NULL,
            entity_id       UUID NOT NULL,
            user_id         UUID NOT NULL REFERENCES users(id),
            activity_type   VARCHAR(100) NOT NULL,
            started_at      TIMESTAMP NOT NULL,
            ended_at        TIMESTAMP,
            duration_seconds INTEGER NOT NULL,
            description     TEXT,
            tempo_synced    TIMESTAMP,
            tempo_worklog_id VARCHAR(100),
            integrity_hash  VARCHAR(64),
            created_at      TIMESTAMP DEFAULT now(),
            metadata        JSONB DEFAULT '{}'
        );

        CREATE INDEX IF NOT EXISTS ix_worklogs_entity_id
            ON worklogs (entity_id);
        CREATE INDEX IF NOT EXISTS ix_worklogs_user_id
            ON worklogs (user_id);
        CREATE INDEX IF NOT EXISTS ix_worklogs_entity_type_entity_id
            ON worklogs (entity_type, entity_id);
    """)


def downgrade() -> None:
    op.execute("DROP TABLE IF EXISTS worklogs")
    op.execute("DROP TABLE IF EXISTS jira_links")
    op.execute("DROP TYPE IF EXISTS jirasyncdirection")
    op.execute("DROP TYPE IF EXISTS jiralinkentitytype")
