"""Initial likes tables

Revision ID: likes_0001
Revises: None
Create Date: 2026-02-27
"""

import sqlalchemy as sa
from alembic import op

revision = "likes_0001"
down_revision = None
branch_labels = None
depends_on = None


def _table_exists(conn, name):
    result = conn.execute(sa.text(
        "SELECT 1 FROM information_schema.tables WHERE table_schema='public' AND table_name=:t"
    ), {"t": name})
    return result.scalar() is not None


def upgrade():
    if _table_exists(op.get_bind(), "likes"):
        return

    op.create_table(
        "likes",
        sa.Column("id", sa.Integer, primary_key=True, autoincrement=True),
        sa.Column("user_id", sa.Integer, nullable=False, index=True),
        sa.Column("target_type", sa.String(32), nullable=False),
        sa.Column("target_slug", sa.String(255), nullable=True),
        sa.Column("target_id", sa.Integer, nullable=True),
        sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
        sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
        sa.Column("deleted_at", sa.DateTime(timezone=True), nullable=True),
        sa.UniqueConstraint("user_id", "target_type", "target_slug",
                            name="uq_likes_user_type_slug"),
        sa.UniqueConstraint("user_id", "target_type", "target_id",
                            name="uq_likes_user_type_id"),
    )
    op.create_index("ix_likes_target", "likes", ["target_type", "target_slug"])


def downgrade():
    op.drop_table("likes")
