CREATE TABLE "dashboards" (
  "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
  "user_id" uuid NOT NULL REFERENCES "users"("id") ON DELETE CASCADE,
  "name" text NOT NULL,
  "slug" text NOT NULL,
  "is_default" boolean NOT NULL DEFAULT false,
  "position" integer NOT NULL DEFAULT 0,
  "layout" jsonb NOT NULL DEFAULT '{"version":1,"widgets":[]}',
  "created_at" timestamp with time zone NOT NULL DEFAULT now(),
  "updated_at" timestamp with time zone NOT NULL DEFAULT now()
);

CREATE UNIQUE INDEX "dashboards_user_slug_uq" ON "dashboards" ("user_id", "slug");

-- Migrate each existing user's default_dashboard_layout into a "Home" dashboard.
-- Idempotent: ON CONFLICT DO NOTHING.
INSERT INTO "dashboards" ("user_id", "name", "slug", "is_default", "position", "layout")
SELECT
  "id",
  'Home',
  'home',
  true,
  0,
  COALESCE("default_dashboard_layout", '{"version":1,"widgets":[]}')
FROM "users"
ON CONFLICT DO NOTHING;

ALTER TABLE "users" DROP COLUMN IF EXISTS "default_dashboard_layout";
