-- ============================================
-- Migration: Adicionar confirmation_status
-- Data: 2025-12-03
-- ============================================
-- INSTRUÇÕES:
-- 1. Acesse https://supabase.com/dashboard
-- 2. Selecione seu projeto
-- 3. Vá em SQL Editor
-- 4. Cole este código completo
-- 5. Clique em RUN
-- ============================================

-- Verificar se a tabela appointments existe
DO $$ 
BEGIN
  IF NOT EXISTS (
    SELECT FROM information_schema.tables 
    WHERE table_schema = 'public' 
    AND table_name = 'appointments'
  ) THEN
    RAISE NOTICE 'AVISO: Tabela appointments não existe. Esta migration será pulada.';
    RAISE NOTICE 'Execute primeiro a migration base que cria as tabelas principais.';
  ELSE
    -- Adicionar coluna confirmation_status
    IF NOT EXISTS (
      SELECT FROM information_schema.columns 
      WHERE table_schema = 'public' 
      AND table_name = 'appointments' 
      AND column_name = 'confirmation_status'
    ) THEN
      ALTER TABLE appointments 
      ADD COLUMN confirmation_status TEXT 
      CHECK (confirmation_status IN ('pending', 'confirmed', 'declined'));
      
      RAISE NOTICE '✓ Coluna confirmation_status adicionada';
    ELSE
      RAISE NOTICE '⊘ Coluna confirmation_status já existe';
    END IF;

    -- Adicionar coluna confirmed_at
    IF NOT EXISTS (
      SELECT FROM information_schema.columns 
      WHERE table_schema = 'public' 
      AND table_name = 'appointments' 
      AND column_name = 'confirmed_at'
    ) THEN
      ALTER TABLE appointments 
      ADD COLUMN confirmed_at TIMESTAMPTZ;
      
      RAISE NOTICE '✓ Coluna confirmed_at adicionada';
    ELSE
      RAISE NOTICE '⊘ Coluna confirmed_at já existe';
    END IF;

    -- Adicionar comentários
    COMMENT ON COLUMN appointments.confirmation_status IS 
      'Status de confirmação de presença do paciente: pending (aguardando), confirmed (confirmado), declined (recusado)';

    COMMENT ON COLUMN appointments.confirmed_at IS 
      'Data e hora em que o paciente confirmou presença na consulta';

    -- Criar índices
    CREATE INDEX IF NOT EXISTS idx_appointments_confirmation_status 
    ON appointments(confirmation_status) 
    WHERE confirmation_status = 'pending';

    CREATE INDEX IF NOT EXISTS idx_appointments_patient_confirmation 
    ON appointments(patient_id, confirmation_status, scheduled_at);

    RAISE NOTICE '✓ Índices criados';

    -- Atualizar consultas existentes
    UPDATE appointments 
    SET confirmation_status = 'pending'
    WHERE confirmation_status IS NULL 
      AND status IN ('requested', 'confirmed')
      AND scheduled_at > NOW();

    UPDATE appointments 
    SET confirmation_status = 'confirmed'
    WHERE confirmation_status IS NULL 
      AND status = 'completed';

    UPDATE appointments 
    SET confirmation_status = 'declined'
    WHERE confirmation_status IS NULL 
    AND status IN ('cancelled', 'no_show');

    RAISE NOTICE '✓ Consultas existentes atualizadas';
    RAISE NOTICE '✓✓ Migration concluída com sucesso!';
  END IF;
END $$;

-- Verificar resultado
SELECT 
  column_name, 
  data_type, 
  is_nullable,
  column_default
FROM information_schema.columns 
WHERE table_name = 'appointments' 
  AND column_name IN ('confirmation_status', 'confirmed_at')
ORDER BY ordinal_position;
