-- Create ticket_inclusions junction table
create table if not exists public.ticket_inclusions (
  id uuid primary key default uuid_generate_v4(),
  ticket_id uuid references public.event_tickets(id) on delete cascade not null,
  menu_item_id uuid references public.menu_items(id) on delete cascade not null,
  quantity int not null default 1,
  created_at timestamptz default now(),
  unique(ticket_id, menu_item_id)
);

-- Enable RLS
alter table public.ticket_inclusions enable row level security;

-- RLS Policies
create policy "Anyone can view ticket inclusions for visible tickets"
  on public.ticket_inclusions for select
  using (
    exists (
      select 1 from public.event_tickets
      where event_tickets.id = ticket_inclusions.ticket_id
      and event_tickets.is_visible = true
    )
  );

create policy "Organizers can manage ticket inclusions"
  on public.ticket_inclusions for all
  using (
    exists (
      select 1 from public.event_tickets
      join public.events on events.id = event_tickets.event_id
      where event_tickets.id = ticket_inclusions.ticket_id
      and events.organizer_id = auth.uid()
    )
  );

-- Create indexes for performance
create index if not exists idx_ticket_inclusions_ticket_id on public.ticket_inclusions(ticket_id);
create index if not exists idx_ticket_inclusions_menu_item_id on public.ticket_inclusions(menu_item_id);
