// PRODUCTION DEPLOY NOTE: This migration is additive-only (CREATE TABLE IF NOT EXISTS +
// 2 indexes, no drops/truncates). Per CLAUDE.md Data Safety, apply to production via
// SSH+docker exec BEFORE pushing Phase 11 schema-dependent code (Plans 02-04).
// Run: npx tsx scripts/push-11-tags-migration.ts (with prod DATABASE_URL)
import postgres from "postgres";

async function push() {
  const databaseUrl = process.env.DATABASE_URL;
  if (!databaseUrl) {
    console.error("DATABASE_URL environment variable is required");
    process.exit(1);
  }

  const client = postgres(databaseUrl);

  try {
    console.log("Pushing tags table migration...");

    await client`
      CREATE TABLE IF NOT EXISTS tags (
        id text PRIMARY KEY,
        entity_type text NOT NULL,
        entity_id text NOT NULL,
        name text NOT NULL,
        created_at timestamp with time zone DEFAULT now() NOT NULL
      )
    `;

    await client`
      CREATE UNIQUE INDEX IF NOT EXISTS tags_entity_name_unique
      ON tags (entity_type, entity_id, name)
    `;

    await client`
      CREATE INDEX IF NOT EXISTS tags_entity_idx
      ON tags (entity_type, entity_id)
    `;

    console.log("✓ tags table created successfully");
    process.exit(0);
  } catch (err: unknown) {
    if (err instanceof Error) {
      if (err.message.includes("already exists")) {
        console.log("✓ tags table already exists (skipped)");
        process.exit(0);
      }
      console.error("Error pushing migration:", err.message);
    } else {
      console.error("Unknown error:", err);
    }
    process.exit(1);
  }
}

push();
