-- RebreakMagic Pairing-Code + Session-Tabellen
-- Native-App generiert 6-stelligen Code, Mac-App tauscht gegen mgc_*-Session-Token.

CREATE TABLE IF NOT EXISTS "rebreak"."magic_pairing_codes" (
  "id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  "user_id" UUID NOT NULL,
  "code" TEXT NOT NULL,
  "expires_at" TIMESTAMP(3) NOT NULL,
  "redeemed_at" TIMESTAMP(3),
  "session_id" UUID,
  "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE UNIQUE INDEX IF NOT EXISTS "magic_pairing_codes_code_key"
  ON "rebreak"."magic_pairing_codes" ("code");
CREATE INDEX IF NOT EXISTS "magic_pairing_codes_user_id_idx"
  ON "rebreak"."magic_pairing_codes" ("user_id");
CREATE INDEX IF NOT EXISTS "magic_pairing_codes_expires_at_idx"
  ON "rebreak"."magic_pairing_codes" ("expires_at");

CREATE TABLE IF NOT EXISTS "rebreak"."magic_sessions" (
  "id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  "user_id" UUID NOT NULL,
  "token" TEXT NOT NULL,
  "label" TEXT,
  "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "last_used_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "revoked_at" TIMESTAMP(3)
);

CREATE UNIQUE INDEX IF NOT EXISTS "magic_sessions_token_key"
  ON "rebreak"."magic_sessions" ("token");
CREATE INDEX IF NOT EXISTS "magic_sessions_user_id_idx"
  ON "rebreak"."magic_sessions" ("user_id");
CREATE INDEX IF NOT EXISTS "magic_sessions_token_idx"
  ON "rebreak"."magic_sessions" ("token");
