-- supabase/migrations/20260411_create_chat_tables.sql

-- Messages table
CREATE TABLE IF NOT EXISTS messages (
  id            uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  channel_id    text NOT NULL REFERENCES tablos(id) ON DELETE CASCADE,
  user_id       uuid NOT NULL REFERENCES auth.users(id),
  text          text NOT NULL,
  created_at    timestamptz NOT NULL DEFAULT now(),
  updated_at    timestamptz,
  deleted_at    timestamptz
);

CREATE INDEX IF NOT EXISTS idx_messages_channel_created ON messages(channel_id, created_at DESC);

-- Read state table
CREATE TABLE IF NOT EXISTS channel_read_state (
  user_id       uuid NOT NULL REFERENCES auth.users(id),
  channel_id    text NOT NULL REFERENCES tablos(id) ON DELETE CASCADE,
  last_read_at  timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (user_id, channel_id)
);

-- RLS policies
ALTER TABLE messages ENABLE ROW LEVEL SECURITY;
ALTER TABLE channel_read_state ENABLE ROW LEVEL SECURITY;

-- Messages: users can read messages in channels they are members of
CREATE POLICY "Users can read messages in their tablos"
  ON messages FOR SELECT
  USING (
    EXISTS (
      SELECT 1 FROM tablo_access
      WHERE tablo_access.tablo_id = messages.channel_id
        AND tablo_access.user_id = auth.uid()
        AND tablo_access.is_active = true
    )
  );

-- Messages: service role inserts (from chat worker) bypass RLS
-- No INSERT policy needed — the chat worker uses the service role key

-- Read state: users can read/write their own read state
CREATE POLICY "Users can manage their own read state"
  ON channel_read_state FOR ALL
  USING (user_id = auth.uid())
  WITH CHECK (user_id = auth.uid());
