-- v69: Crate inventory and live Discord crate drops
CREATE TABLE IF NOT EXISTS public.user_crates_inventory (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id uuid NOT NULL REFERENCES public.profiles(id) ON DELETE CASCADE,
  crate_id text NOT NULL,
  source text NOT NULL DEFAULT 'purchase',
  opened boolean NOT NULL DEFAULT false,
  opened_at timestamptz,
  loot_result jsonb,
  created_at timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_user_crates_inventory_unopened
  ON public.user_crates_inventory (user_id, opened, crate_id);

CREATE INDEX IF NOT EXISTS idx_user_crates_inventory_user
  ON public.user_crates_inventory (user_id, created_at DESC);

ALTER TABLE public.user_crates_inventory ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Users can view their own crate inventory"
  ON public.user_crates_inventory
  FOR SELECT
  TO authenticated
  USING (auth.uid() = user_id);

-- Discord Live Crate Drops
CREATE TABLE IF NOT EXISTS public.discord_crate_drops (
  drop_id text PRIMARY KEY,
  channel_id text NOT NULL,
  message_id text,
  crate_id text NOT NULL,
  max_claims integer NOT NULL DEFAULT 5,
  created_at timestamptz NOT NULL DEFAULT now()
);

ALTER TABLE public.discord_crate_drops ENABLE ROW LEVEL SECURITY;

CREATE TABLE IF NOT EXISTS public.discord_crate_drop_claims (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  drop_id text NOT NULL,
  discord_user_id text NOT NULL,
  user_id uuid NOT NULL REFERENCES public.profiles(id) ON DELETE CASCADE,
  username text NOT NULL,
  crate_id text NOT NULL,
  inventory_id uuid REFERENCES public.user_crates_inventory(id) ON DELETE SET NULL,
  seen_on_site boolean NOT NULL DEFAULT false,
  created_at timestamptz NOT NULL DEFAULT now(),
  UNIQUE (drop_id, user_id)
);

CREATE INDEX IF NOT EXISTS idx_discord_crate_drop_claims_unseen
  ON public.discord_crate_drop_claims (user_id, seen_on_site)
  WHERE seen_on_site = false;

CREATE INDEX IF NOT EXISTS idx_discord_crate_drop_claims_drop
  ON public.discord_crate_drop_claims (drop_id);

ALTER TABLE public.discord_crate_drop_claims ENABLE ROW LEVEL SECURITY;
