-- Simplify Google Calendar integration to use public calendars only
-- No OAuth needed - just store calendar ID and fetch with API key

-- Drop the old OAuth-based table
DROP TABLE IF EXISTS org_google_calendars CASCADE;
DROP TABLE IF EXISTS google_calendar_connections CASCADE;

-- Create simplified org calendar table
CREATE TABLE IF NOT EXISTS org_google_calendars (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  org_id UUID REFERENCES organizations(id) ON DELETE CASCADE UNIQUE,
  calendar_id TEXT NOT NULL, -- The public calendar ID (email format)
  calendar_name TEXT, -- Display name
  connected_by UUID REFERENCES auth.users(id),
  created_at TIMESTAMPTZ DEFAULT now(),
  updated_at TIMESTAMPTZ DEFAULT now()
);

-- RLS policies
ALTER TABLE org_google_calendars ENABLE ROW LEVEL SECURITY;

-- Members can view org calendar
CREATE POLICY "Members can view org calendar" ON org_google_calendars
  FOR SELECT USING (
    EXISTS (
      SELECT 1 FROM org_members
      WHERE org_members.org_id = org_google_calendars.org_id
      AND org_members.user_id = auth.uid()
    )
  );

-- Admins/owners can manage org calendar
CREATE POLICY "Admins can manage org calendar" ON org_google_calendars
  FOR ALL USING (
    EXISTS (
      SELECT 1 FROM org_members
      WHERE org_members.org_id = org_google_calendars.org_id
      AND org_members.user_id = auth.uid()
      AND org_members.role IN ('admin', 'owner')
    )
  );

-- Enable realtime
ALTER PUBLICATION supabase_realtime ADD TABLE org_google_calendars;
