import { db, appsTable } from "@workspace/db";
import { and, eq } from "drizzle-orm";

// #603: One-shot migration that bumps the seeded app colours on
// existing installs to the new #603 palette. The seed itself uses
// `onConflictDoNothing` on `slug`, so previously-seeded rows would
// otherwise keep their old hex values forever and continue to render
// as three identical blue tiles on the home screen.
//
// Each update is gated on the row STILL holding the old default —
// admins who customised an app colour from the Apps editor keep their
// choice untouched.
const MIGRATIONS: Array<{ slug: string; from: string; to: string }> = [
  // Meetings: dark navy → green (was falling through to default blue).
  { slug: "executive-meetings", from: "#0B1E3F", to: "#22c55e" },
  // Notifications: purple → cyan (purple is no longer in the palette).
  { slug: "notifications", from: "#8b5cf6", to: "#06b6d4" },
];

async function main(): Promise<void> {
  console.log("Migrating app colours to the #603 palette...");
  let touched = 0;
  for (const m of MIGRATIONS) {
    const updated = await db
      .update(appsTable)
      .set({ color: m.to })
      .where(and(eq(appsTable.slug, m.slug), eq(appsTable.color, m.from)))
      .returning({ slug: appsTable.slug, color: appsTable.color });
    if (updated.length === 0) {
      console.log(
        `  - ${m.slug}: skipped (row missing or already customised)`,
      );
    } else {
      touched += updated.length;
      for (const row of updated) {
        console.log(`  - ${row.slug}: color → ${row.color}`);
      }
    }
  }
  console.log(`Done. Rows updated: ${touched}.`);
}

main()
  .catch((err) => {
    console.error(err);
    process.exit(1);
  })
  .finally(() => process.exit(0));
