import { db } from "@/db";
import { services, tags } from "@/db/schema";
import { eq, and } from "drizzle-orm";

async function migrate() {
  console.log("Starting tags migration: assigning 'Offerta' tag to services migrated from offer_services...\n");

  const offerServices = await db
    .select({ id: services.id })
    .from(services)
    .where(eq(services.migrated_from, "offer_services"));

  let taggedCount = 0;
  let skippedCount = 0;

  for (const service of offerServices) {
    const existing = await db
      .select()
      .from(tags)
      .where(
        and(
          eq(tags.entity_type, "services"),
          eq(tags.entity_id, service.id),
          eq(tags.name, "Offerta")
        )
      )
      .limit(1);

    if (existing.length > 0) {
      skippedCount++;
      continue;
    }

    await db.insert(tags).values({
      entity_type: "services",
      entity_id: service.id,
      name: "Offerta",
    });
    taggedCount++;
  }

  console.log(`Assigned 'Offerta' tag: ${taggedCount} services, ${skippedCount} already tagged`);
  console.log("\nMigration complete. Run scripts/validate-tags-migration.ts next.");
  process.exit(0);
}

migrate().catch((err) => {
  console.error("Migration failed:", err);
  process.exit(1);
});
