"""cps_link / cps_click tables (群发短链 + 点击统计)

Revision ID: cps_link_tables
Revises: cps_tables
Create Date: 2026-06-16 13:20:00.000000

群发券链接套一层 /c/{code} 做点击统计:cps_link(短码→美团目标) + cps_click(点击事件)。
"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


revision: str = "cps_link_tables"
down_revision: Union[str, Sequence[str], None] = "cps_tables"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None

_NOW = sa.text("CURRENT_TIMESTAMP")


def upgrade() -> None:
    op.create_table(
        "cps_link",
        sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
        sa.Column("code", sa.String(length=16), nullable=False),
        sa.Column("group_id", sa.Integer(), nullable=False),
        sa.Column("activity_id", sa.Integer(), nullable=False),
        sa.Column("sid", sa.String(length=64), nullable=False),
        sa.Column("platform", sa.String(length=20), nullable=False, server_default="meituan"),
        sa.Column("target_url", sa.String(length=1024), nullable=False),
        sa.Column("created_at", sa.DateTime(timezone=True), server_default=_NOW, nullable=False),
        sa.PrimaryKeyConstraint("id"),
        sa.UniqueConstraint("code", name="uq_cps_link_code"),
    )
    op.create_index("ix_cps_link_code", "cps_link", ["code"])
    op.create_index("ix_cps_link_group_id", "cps_link", ["group_id"])
    op.create_index("ix_cps_link_activity_id", "cps_link", ["activity_id"])
    op.create_index("ix_cps_link_sid", "cps_link", ["sid"])

    op.create_table(
        "cps_click",
        sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
        sa.Column("link_id", sa.Integer(), nullable=False),
        sa.Column("group_id", sa.Integer(), nullable=False),
        sa.Column("sid", sa.String(length=64), nullable=False),
        sa.Column("ip", sa.String(length=64), nullable=True),
        sa.Column("ua", sa.String(length=512), nullable=True),
        sa.Column("clicked_at", sa.DateTime(timezone=True), server_default=_NOW, nullable=False),
        sa.PrimaryKeyConstraint("id"),
    )
    op.create_index("ix_cps_click_link_id", "cps_click", ["link_id"])
    op.create_index("ix_cps_click_group_id", "cps_click", ["group_id"])
    op.create_index("ix_cps_click_sid", "cps_click", ["sid"])
    op.create_index("ix_cps_click_clicked_at", "cps_click", ["clicked_at"])


def downgrade() -> None:
    op.drop_table("cps_click")
    op.drop_table("cps_link")
