ALTER TABLE "users" ADD COLUMN "username" TEXT;

WITH ranked AS (
  SELECT
    id,
    CASE
      WHEN lower(regexp_replace(split_part(email, '@', 1), '[^a-zA-Z0-9_-]', '-', 'g')) = ''
        THEN CONCAT('user-', substring(id from 1 for 6))
      ELSE lower(regexp_replace(split_part(email, '@', 1), '[^a-zA-Z0-9_-]', '-', 'g'))
    END AS base,
    ROW_NUMBER() OVER (
      PARTITION BY CASE
        WHEN lower(regexp_replace(split_part(email, '@', 1), '[^a-zA-Z0-9_-]', '-', 'g')) = ''
          THEN CONCAT('user-', substring(id from 1 for 6))
        ELSE lower(regexp_replace(split_part(email, '@', 1), '[^a-zA-Z0-9_-]', '-', 'g'))
      END
      ORDER BY created_at, id
    ) AS rn
  FROM "users"
)
UPDATE "users" AS u
SET "username" = CASE
  WHEN ranked.rn = 1 THEN ranked.base
  ELSE CONCAT(ranked.base, '-', ranked.rn)
END
FROM ranked
WHERE u.id = ranked.id;

ALTER TABLE "users" ALTER COLUMN "username" SET NOT NULL;
ALTER TABLE "users" ALTER COLUMN "email" DROP NOT NULL;
CREATE UNIQUE INDEX "users_username_key" ON "users"("username");

CREATE TABLE "budgets" (
  "id" TEXT NOT NULL,
  "name" TEXT NOT NULL,
  "total_budget" DECIMAL(10,2) NOT NULL,
  "color_code" TEXT NOT NULL,
  "working_group_id" TEXT NOT NULL,
  "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "updated_at" TIMESTAMP(3) NOT NULL,
  CONSTRAINT "budgets_pkey" PRIMARY KEY ("id")
);

INSERT INTO "budgets" (
  "id",
  "name",
  "total_budget",
  "color_code",
  "working_group_id",
  "created_at",
  "updated_at"
)
SELECT
  CONCAT('budget_', "id"),
  'Hauptbudget',
  "total_budget",
  "color_code",
  "id",
  "created_at",
  "updated_at"
FROM "working_groups";

CREATE UNIQUE INDEX "budgets_working_group_id_name_key" ON "budgets"("working_group_id", "name");

ALTER TABLE "budgets"
  ADD CONSTRAINT "budgets_working_group_id_fkey"
  FOREIGN KEY ("working_group_id") REFERENCES "working_groups"("id")
  ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE "expenses" RENAME COLUMN "notes" TO "description";
ALTER TABLE "expenses" ADD COLUMN "budget_id" TEXT;

UPDATE "expenses"
SET "budget_id" = CONCAT('budget_', "ag_id");

ALTER TABLE "expenses" ALTER COLUMN "budget_id" SET NOT NULL;

ALTER TABLE "expenses"
  ADD CONSTRAINT "expenses_budget_id_fkey"
  FOREIGN KEY ("budget_id") REFERENCES "budgets"("id")
  ON DELETE RESTRICT ON UPDATE CASCADE;

ALTER TABLE "working_groups" DROP COLUMN "total_budget";
ALTER TABLE "working_groups" DROP COLUMN "color_code";
