-- Criar schema portal
CREATE SCHEMA IF NOT EXISTS portal;

-- Criar função para atualizar updated_at automaticamente
CREATE OR REPLACE FUNCTION portal.update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
  NEW.updated_at = NOW();
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

-- Criar tabela user_settings
CREATE TABLE portal.user_settings (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW(),
  UNIQUE(user_id)
);

-- Criar índice explícito para FK (performance)
CREATE INDEX idx_user_settings_user_id ON portal.user_settings(user_id);

-- Trigger para atualizar updated_at automaticamente
CREATE TRIGGER update_user_settings_updated_at
  BEFORE UPDATE ON portal.user_settings
  FOR EACH ROW
  EXECUTE FUNCTION portal.update_updated_at_column();

-- Criar tabela integrations (para armazenar status OAuth)
CREATE TABLE portal.integrations (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE,
  provider VARCHAR(50) NOT NULL, -- 'google_calendar'
  status VARCHAR(20) DEFAULT 'disconnected', -- 'connected', 'disconnected'
  connected_at TIMESTAMPTZ,
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW(),
  UNIQUE(user_id, provider)
);

-- Criar índice explícito para FK (performance)
CREATE INDEX idx_integrations_user_id ON portal.integrations(user_id);

-- Trigger para atualizar updated_at automaticamente
CREATE TRIGGER update_integrations_updated_at
  BEFORE UPDATE ON portal.integrations
  FOR EACH ROW
  EXECUTE FUNCTION portal.update_updated_at_column();

-- Habilitar RLS
ALTER TABLE portal.user_settings ENABLE ROW LEVEL SECURITY;
ALTER TABLE portal.integrations ENABLE ROW LEVEL SECURITY;

-- Políticas RLS (usuários só veem seus próprios dados)
CREATE POLICY "Users can view own settings"
  ON portal.user_settings
  FOR SELECT
  USING (auth.uid() = user_id);

CREATE POLICY "Users can update own settings"
  ON portal.user_settings
  FOR UPDATE
  USING (auth.uid() = user_id);

CREATE POLICY "Users can insert own settings"
  ON portal.user_settings
  FOR INSERT
  WITH CHECK (auth.uid() = user_id);

CREATE POLICY "Users can view own integrations"
  ON portal.integrations
  FOR SELECT
  USING (auth.uid() = user_id);

CREATE POLICY "Users can update own integrations"
  ON portal.integrations
  FOR UPDATE
  USING (auth.uid() = user_id);

CREATE POLICY "Users can insert own integrations"
  ON portal.integrations
  FOR INSERT
  WITH CHECK (auth.uid() = user_id);

-- Políticas DELETE (LGPD/GDPR compliance - direito ao esquecimento)
CREATE POLICY "Users can delete own settings"
  ON portal.user_settings
  FOR DELETE
  USING (auth.uid() = user_id);

CREATE POLICY "Users can delete own integrations"
  ON portal.integrations
  FOR DELETE
  USING (auth.uid() = user_id);
