-- Organization-level Google Calendar (shared across all members)

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, -- Google Calendar ID (e.g., "abc123@group.calendar.google.com")
  calendar_name TEXT,
  connected_by UUID REFERENCES auth.users(id),
  access_token TEXT NOT NULL,
  refresh_token TEXT NOT NULL,
  token_expires_at TIMESTAMPTZ NOT NULL,
  created_at TIMESTAMPTZ DEFAULT now(),
  updated_at TIMESTAMPTZ DEFAULT now()
);

-- Index
CREATE INDEX IF NOT EXISTS idx_org_google_calendars_org ON org_google_calendars(org_id);

-- RLS
ALTER TABLE org_google_calendars ENABLE ROW LEVEL SECURITY;

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

-- Only 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 om 
    WHERE om.org_id = org_google_calendars.org_id 
    AND om.user_id = auth.uid() 
    AND om.role IN ('owner', 'admin')
  ));
