-- Parcel Empire Production Hardening
-- Run AFTER sql/supabase_schema.sql, then run sql/supabase_security_patch.sql.

-- Helpful indexes that match columns present in the current schema.
create index if not exists idx_atlas_parcels_owner_id
on public.atlas_parcels(owner_id);

create index if not exists idx_atlas_parcels_updated_at
on public.atlas_parcels(updated_at desc);

create index if not exists idx_atlas_marketplace_status
on public.atlas_marketplace(status);

create index if not exists idx_atlas_marketplace_seller
on public.atlas_marketplace(seller_id);

create index if not exists idx_atlas_leaderboard_score
on public.atlas_leaderboard(score desc);

create index if not exists idx_atlas_transactions_user_created
on public.atlas_transactions(user_id, created_at desc);

create index if not exists idx_atlas_payout_requests_user_created
on public.atlas_payout_requests(user_id, created_at desc);

-- Confirm RLS on every sensitive table used by the current game.
alter table if exists public.atlas_profiles enable row level security;
alter table if exists public.atlas_wallets enable row level security;
alter table if exists public.atlas_transactions enable row level security;
alter table if exists public.atlas_payout_requests enable row level security;
alter table if exists public.atlas_payout_profiles enable row level security;
alter table if exists public.parcel_player_profiles enable row level security;
alter table if exists public.atlas_parcels enable row level security;
alter table if exists public.atlas_marketplace enable row level security;
alter table if exists public.atlas_leaderboard enable row level security;
alter table if exists public.atlas_admins enable row level security;
alter table if exists public.atlas_admin_audit enable row level security;

-- Owner-read policies. Duplicate policy errors are safely ignored.
do $$ begin
  create policy "wallet owner can read own wallet"
  on public.atlas_wallets for select
  to authenticated
  using (auth.uid() = user_id);
exception when duplicate_object then null; end $$;

do $$ begin
  create policy "transactions owner can read own transactions"
  on public.atlas_transactions for select
  to authenticated
  using (auth.uid() = user_id);
exception when duplicate_object then null; end $$;

do $$ begin
  create policy "payout owner can read own requests"
  on public.atlas_payout_requests for select
  to authenticated
  using (auth.uid() = user_id);
exception when duplicate_object then null; end $$;

-- The previous package attempted to index atlas_parcels(lat, lng), but those
-- columns do not exist in the current schema. That invalid index was removed.
