DO $$
BEGIN
  CREATE TYPE "UserStatus" AS ENUM ('invited', 'active', 'inactive', 'suspended');
EXCEPTION
  WHEN duplicate_object THEN NULL;
END $$;

ALTER TYPE "UserStatus" ADD VALUE IF NOT EXISTS 'invited';

ALTER TABLE "users"
  ALTER COLUMN "status" DROP DEFAULT;

UPDATE "users"
SET "status" = 'active'
WHERE "status" IS NULL OR "status"::text = 'active';

ALTER TABLE "users"
  ALTER COLUMN "status" TYPE "UserStatus"
  USING CASE
    WHEN "status" IS NULL THEN 'invited'::"UserStatus"
    WHEN "status"::text = 'active' THEN 'active'::"UserStatus"
    WHEN "status"::text = 'inactive' THEN 'inactive'::"UserStatus"
    WHEN "status"::text = 'suspended' THEN 'suspended'::"UserStatus"
    WHEN "status"::text = 'invited' THEN 'invited'::"UserStatus"
    ELSE 'invited'::"UserStatus"
  END;

ALTER TABLE "users"
  ALTER COLUMN "password_hash" DROP NOT NULL,
  ALTER COLUMN "status" SET DEFAULT 'invited',
  ADD COLUMN IF NOT EXISTS "invite_token_hash" TEXT,
  ADD COLUMN IF NOT EXISTS "invite_token_expires_at" TIMESTAMP(3),
  ADD COLUMN IF NOT EXISTS "email_verified_at" TIMESTAMP(3),
  ADD COLUMN IF NOT EXISTS "last_login_at" TIMESTAMP(3);
CREATE INDEX IF NOT EXISTS "users_invite_token_hash_idx" ON "users"("invite_token_hash");
