-- Chat messages for swap request bargaining
CREATE TABLE IF NOT EXISTS chat_messages (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  thread_id uuid NOT NULL,
  sender_id uuid NOT NULL REFERENCES auth.users(id),
  body text NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX idx_chat_messages_thread ON chat_messages (thread_id, created_at);

-- Auto-generate chat_thread_id on swap_requests if null
ALTER TABLE swap_requests ALTER COLUMN chat_thread_id SET DEFAULT gen_random_uuid();

-- Backfill existing swap_requests that have no chat_thread_id
UPDATE swap_requests SET chat_thread_id = gen_random_uuid() WHERE chat_thread_id IS NULL;

-- Enable realtime
ALTER PUBLICATION supabase_realtime ADD TABLE chat_messages;

-- RLS
ALTER TABLE chat_messages ENABLE ROW LEVEL SECURITY;

-- Users can read messages for swap requests where they are requester or recipient
CREATE POLICY "chat_messages_select" ON chat_messages FOR SELECT TO authenticated
USING (
  EXISTS (
    SELECT 1 FROM swap_requests sr
    WHERE sr.chat_thread_id = chat_messages.thread_id
      AND (sr.requester_id = auth.uid() OR sr.recipient_id = auth.uid())
  )
  OR EXISTS (
    SELECT 1 FROM profiles p WHERE p.id = auth.uid() AND p.role IN ('admin', 'dispatcher')
  )
);

-- Users can insert messages for swap requests where they are requester or recipient
CREATE POLICY "chat_messages_insert" ON chat_messages FOR INSERT TO authenticated
WITH CHECK (
  sender_id = auth.uid()
  AND EXISTS (
    SELECT 1 FROM swap_requests sr
    WHERE sr.chat_thread_id = chat_messages.thread_id
      AND (sr.requester_id = auth.uid() OR sr.recipient_id = auth.uid())
  )
);
