import { createClient } from '@/lib/supabase'
import type { Question, Survey } from '@/lib/types'
import { SurveyForm } from '@/components/survey-form'

// Force dynamic rendering — page fetches from Supabase at request time.
// Never statically generated: credentials live in .env.local (runtime only).
export const dynamic = 'force-dynamic'

// Server Component — fetches survey with anon key; RLS ensures only status='live' is returned.
export default async function Page() {
  const supabase = createClient()

  // 1. Fetch the live survey
  const { data: surveyRow, error: surveyError } = await supabase
    .from('surveys')
    .select('id, title, status, is_anonymous, k_threshold')
    .eq('status', 'live')
    .maybeSingle()

  if (surveyError) {
    return (
      <div className="no-survey" role="main">
        <h1 className="no-survey-title">Error al cargar la encuesta</h1>
        <p>No fue posible conectarse a la base de datos. Revisá las variables de entorno.</p>
        <pre className="no-survey-hint">{surveyError.message}</pre>
      </div>
    )
  }

  if (!surveyRow) {
    return (
      <div className="no-survey" role="main">
        <h1 className="no-survey-title">No hay encuesta activa</h1>
        <p>
          Para ver el formulario, la encuesta debe estar en estado <code>live</code>.
        </p>
        <pre className="no-survey-hint">
          {`-- Activar la encuesta en Supabase Cloud:\nUPDATE surveys\nSET status = 'live'\nWHERE id = '30000000-0000-0000-0000-000000000001';`}
        </pre>
      </div>
    )
  }

  // 2. Fetch questions ordered by position
  const { data: questionRows, error: questionsError } = await supabase
    .from('questions')
    .select(
      'id, survey_id, code, type, prompt, position, is_sensitive, required, max_select, options, conditional_rules'
    )
    .eq('survey_id', surveyRow.id)
    .order('position', { ascending: true })

  if (questionsError || !questionRows) {
    return (
      <div className="no-survey" role="main">
        <h1 className="no-survey-title">Error al cargar las preguntas</h1>
        <p>{questionsError?.message ?? 'Respuesta vacía del servidor.'}</p>
      </div>
    )
  }

  const questions = questionRows as Question[]

  // 3. Log question count for validation (visible in server logs and browser Network tab)
  console.log(
    `[2A] Survey loaded: id=${surveyRow.id} | questions=${questions.length}`
  )

  const survey: Survey = {
    ...(surveyRow as Omit<Survey, 'questions'>),
    questions,
  }

  return (
    <SurveyForm
      survey={survey}
      questions={questions}
    />
  )
}
