-- AlterTable: Branch — yeni alanlar ekle
ALTER TABLE "branches" ADD COLUMN IF NOT EXISTS "email"         TEXT;
ALTER TABLE "branches" ADD COLUMN IF NOT EXISTS "logo_url"      TEXT;
ALTER TABLE "branches" ADD COLUMN IF NOT EXISTS "slogan"        TEXT;
ALTER TABLE "branches" ADD COLUMN IF NOT EXISTS "gallery_images" JSONB;
ALTER TABLE "branches" ADD COLUMN IF NOT EXISTS "manager_id"    TEXT;
ALTER TABLE "branches" ADD COLUMN IF NOT EXISTS "updated_at"    TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP;

-- AlterTable: User — şube çalışma alanı
ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "branch_id" TEXT;

-- Index: Branch.managerId
CREATE INDEX IF NOT EXISTS "branches_manager_id_idx" ON "branches"("manager_id");

-- Index: User.branchId
CREATE INDEX IF NOT EXISTS "users_branch_id_idx" ON "users"("branch_id");

-- ForeignKey: Branch.managerId → User.id
DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM information_schema.table_constraints
    WHERE constraint_name = 'branches_manager_id_fkey'
  ) THEN
    ALTER TABLE "branches"
      ADD CONSTRAINT "branches_manager_id_fkey"
      FOREIGN KEY ("manager_id") REFERENCES "users"("id")
      ON DELETE SET NULL ON UPDATE CASCADE;
  END IF;
END $$;

-- ForeignKey: User.branchId → Branch.id
DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM information_schema.table_constraints
    WHERE constraint_name = 'users_branch_id_fkey'
  ) THEN
    ALTER TABLE "users"
      ADD CONSTRAINT "users_branch_id_fkey"
      FOREIGN KEY ("branch_id") REFERENCES "branches"("id")
      ON DELETE SET NULL ON UPDATE CASCADE;
  END IF;
END $$;
