-- Delete duplicate admin users first (keep the one with lowest id)
DELETE FROM "users" WHERE "email" = 'admin@wraith.local' AND "id" != (SELECT MIN("id") FROM "users" WHERE "email" = 'admin@wraith.local');

-- Add role to users
ALTER TABLE "users" ADD COLUMN "role" TEXT NOT NULL DEFAULT 'user';

-- Backfill admin@wraith.local as admin
UPDATE "users" SET "role" = 'admin' WHERE "email" = 'admin@wraith.local';

-- Add user_id to all data tables
ALTER TABLE "hosts" ADD COLUMN "user_id" INTEGER;
ALTER TABLE "host_groups" ADD COLUMN "user_id" INTEGER;
ALTER TABLE "credentials" ADD COLUMN "user_id" INTEGER;
ALTER TABLE "ssh_keys" ADD COLUMN "user_id" INTEGER;
ALTER TABLE "connection_logs" ADD COLUMN "user_id" INTEGER;

-- Backfill existing data to the admin user
UPDATE "hosts" SET "user_id" = (SELECT "id" FROM "users" WHERE "email" = 'admin@wraith.local');
UPDATE "host_groups" SET "user_id" = (SELECT "id" FROM "users" WHERE "email" = 'admin@wraith.local');
UPDATE "credentials" SET "user_id" = (SELECT "id" FROM "users" WHERE "email" = 'admin@wraith.local');
UPDATE "ssh_keys" SET "user_id" = (SELECT "id" FROM "users" WHERE "email" = 'admin@wraith.local');
UPDATE "connection_logs" SET "user_id" = (SELECT "id" FROM "users" WHERE "email" = 'admin@wraith.local');

-- Make user_id NOT NULL after backfill
ALTER TABLE "hosts" ALTER COLUMN "user_id" SET NOT NULL;
ALTER TABLE "host_groups" ALTER COLUMN "user_id" SET NOT NULL;
ALTER TABLE "credentials" ALTER COLUMN "user_id" SET NOT NULL;
ALTER TABLE "ssh_keys" ALTER COLUMN "user_id" SET NOT NULL;
ALTER TABLE "connection_logs" ALTER COLUMN "user_id" SET NOT NULL;

-- Add foreign keys
ALTER TABLE "hosts" ADD CONSTRAINT "hosts_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE;
ALTER TABLE "host_groups" ADD CONSTRAINT "host_groups_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE;
ALTER TABLE "credentials" ADD CONSTRAINT "credentials_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE;
ALTER TABLE "ssh_keys" ADD CONSTRAINT "ssh_keys_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE;
ALTER TABLE "connection_logs" ADD CONSTRAINT "connection_logs_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE;
