ALTER TABLE "employees" ADD COLUMN "prefix" text;--> statement-breakpoint
ALTER TABLE "employees" ADD COLUMN "first_name_th" text;--> statement-breakpoint
ALTER TABLE "employees" ADD COLUMN "last_name_th" text;--> statement-breakpoint
ALTER TABLE "employees" ADD COLUMN "first_name_en" text;--> statement-breakpoint
ALTER TABLE "employees" ADD COLUMN "last_name_en" text;--> statement-breakpoint
ALTER TABLE "employees" ADD COLUMN "display_name" text;--> statement-breakpoint
ALTER TABLE "employees" ADD COLUMN "phone" text;--> statement-breakpoint
ALTER TABLE "employees" ADD COLUMN "company_name" text;--> statement-breakpoint
ALTER TABLE "employees" ADD COLUMN "status" text DEFAULT 'active' NOT NULL;--> statement-breakpoint
ALTER TABLE "users" ADD COLUMN "provider" text DEFAULT 'credentials' NOT NULL;--> statement-breakpoint
ALTER TABLE "users" ADD COLUMN "provider_user_id" text;--> statement-breakpoint
ALTER TABLE "users" ADD COLUMN "employee_id" integer;--> statement-breakpoint
ALTER TABLE "users" ADD COLUMN "last_login_at" timestamp with time zone;--> statement-breakpoint
ALTER TABLE "employee_training_targets" ADD COLUMN "employee_id" integer;--> statement-breakpoint
ALTER TABLE "employee_training_targets" ADD CONSTRAINT "employee_training_targets_employee_id_employees_id_fk" FOREIGN KEY ("employee_id") REFERENCES "public"."employees"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "users" ADD CONSTRAINT "users_employee_id_employees_id_fk" FOREIGN KEY ("employee_id") REFERENCES "public"."employees"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
CREATE UNIQUE INDEX "users_provider_user_id_idx" ON "users" USING btree ("provider","provider_user_id");--> statement-breakpoint

UPDATE "employees"
SET
  "display_name" = COALESCE("display_name", "full_name"),
  "company_name" = COALESCE("company_name", "company"),
  "status" = CASE WHEN "is_active" = true THEN 'active' ELSE 'inactive' END;--> statement-breakpoint

UPDATE "users"
SET "provider" = COALESCE("provider", 'credentials')
WHERE "provider" IS NULL;--> statement-breakpoint

UPDATE "users" u
SET "employee_id" = e."id"
FROM "memberships" m
INNER JOIN "employees" e
  ON e."organization_id" = m."organization_id"
 AND e."employee_code" = u."employee_code"
WHERE m."user_id" = u."id"
  AND u."employee_code" IS NOT NULL
  AND (u."employee_id" IS NULL OR u."employee_id" <> e."id");--> statement-breakpoint

UPDATE "training_records" tr
SET "employee_id" = u."employee_id"
FROM "users" u
WHERE tr."user_id" = u."id"
  AND tr."employee_id" IS NULL
  AND u."employee_id" IS NOT NULL;--> statement-breakpoint

UPDATE "employee_training_targets" ett
SET "employee_id" = u."employee_id"
FROM "users" u
WHERE ett."user_id" = u."id"
  AND ett."employee_id" IS NULL
  AND u."employee_id" IS NOT NULL;
