/*
  Warnings:

  - A unique constraint covering the columns `[userId]` on the table `siswa` will be added. If there are existing duplicate values, this will fail.
  - A unique constraint covering the columns `[username]` on the table `users` will be added. If there are existing duplicate values, this will fail.
  - Added the required column `userId` to the `siswa` table without a default value. This is not possible if the table is not empty.
  - Added the required column `username` to the `users` table without a default value. This is not possible if the table is not empty.

*/

-- First, add username column with default value for existing users
ALTER TABLE "users" ADD COLUMN "username" TEXT;

-- Update existing users with a default username based on email
UPDATE "users" SET "username" = SPLIT_PART("email", '@', 1) WHERE "username" IS NULL;

-- Make username NOT NULL and UNIQUE
ALTER TABLE "users" ALTER COLUMN "username" SET NOT NULL;

-- Add userId column to siswa table (optional for now)
ALTER TABLE "siswa" ADD COLUMN "userId" TEXT;

-- For existing siswa records, we'll leave userId as NULL since we can't automatically link them to users
-- New siswa records from import will have proper userId values

-- Create indexes
CREATE UNIQUE INDEX "users_username_key" ON "users"("username");

-- We'll add the foreign key constraint but make it optional for existing records
-- AddForeignKey (only for records that have userId)
ALTER TABLE "siswa" ADD CONSTRAINT "siswa_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
