// tdd-guard:skip — Next.js route handler; read-only status aggregation.
import { NextResponse } from 'next/server'
import { getUserSession } from '@/lib/auth/permissions'
import { isAtLeastRole } from '@/lib/auth/permissions-shared'
import { createAdminClient } from '@/lib/supabase/admin'
import type { DemoStatus } from '@/lib/demo/demo-service'
import { DEMO_INTAKE_IDS, DEMO_TOP_MGMT_PROJECT_ID, DEMO_VSM_IDS } from '@/lib/demo/demo-ids'

export async function GET() {
  const session = await getUserSession()
  if (!session || !isAtLeastRole(session, 'admin')) {
    return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
  }

  const admin = createAdminClient()

  const [
    { count: projectCount },
    { count: assignmentCount },
    { count: stepCount },
    { count: assessmentCount },
    { count: oeeCount },
    { count: vsmCount },
    { count: documentCount },
    { count: intakeCount },
    { count: topMgmtCount },
  ] = await Promise.all([
    admin.from('projects').select('id', { count: 'exact', head: true }).eq('is_demo', true),
    admin.from('assignments').select('id', { count: 'exact', head: true }).eq('is_demo', true),
    admin.from('process_steps').select('id', { count: 'exact', head: true }).eq('is_demo', true),
    admin.from('assessments').select('id', { count: 'exact', head: true }).eq('is_demo', true),
    admin.from('oee_records').select('id', { count: 'exact', head: true }).eq('is_demo', true),
    // Count by the stable seed ids (same pattern as intakes below), NOT by
    // is_demo alone: user-created demo-flagged VSMs (e.g. QAF-derived demo
    // cards) would otherwise mask an incomplete seed set — and completeness
    // is what `loaded` must express so the DemoSuggestionCard can offer
    // re-seeding when a release ships NEW seed entries (Referenzwertstrom
    // was invisible to existing installs before this).
    admin.from('value_stream_maps').select('id', { count: 'exact', head: true }).in('id', [...DEMO_VSM_IDS]),
    admin.from('documents').select('id', { count: 'exact', head: true }).eq('is_demo', true),
    // intakes has no is_demo column — count by the stable demo id range.
    admin.from('intakes').select('id', { count: 'exact', head: true }).in('id', [...DEMO_INTAKE_IDS]),
    // top_management_demo is its own project (not the shared is_demo pool
    // above) — counted by its own stable project id.
    admin.from('projects').select('id', { count: 'exact', head: true }).eq('id', DEMO_TOP_MGMT_PROJECT_ID),
  ])

  const status: DemoStatus = {
    active:
      (projectCount ?? 0) > 0 ||
      (assignmentCount ?? 0) > 0 ||
      (stepCount ?? 0) > 0 ||
      (assessmentCount ?? 0) > 0 ||
      (oeeCount ?? 0) > 0 ||
      (vsmCount ?? 0) > 0 ||
      (documentCount ?? 0) > 0 ||
      (intakeCount ?? 0) > 0 ||
      (topMgmtCount ?? 0) > 0,
    modules: [
      { module: 'projektanlage', label: 'Projektanlage',         loaded: (projectCount ?? 0) > 0,    count: projectCount ?? 0 },
      { module: 'kalender',      label: 'Kalender',              loaded: (assignmentCount ?? 0) > 0,  count: assignmentCount ?? 0 },
      { module: 'lsc-workshop',  label: 'LSC Workshop',          loaded: (stepCount ?? 0) > 0,        count: stepCount ?? 0 },
      { module: 'fabrikanalyse', label: 'Fabrikanalyse',         loaded: (assessmentCount ?? 0) > 0,  count: assessmentCount ?? 0 },
      { module: 'oee',           label: 'OEE Analyse',           loaded: (oeeCount ?? 0) > 0,         count: oeeCount ?? 0 },
      { module: 'wertstrom',     label: 'Wertstromanalyse',      loaded: (vsmCount ?? 0) >= DEMO_VSM_IDS.length, count: vsmCount ?? 0 },
      { module: 'datenablage',   label: 'Datenablage',           loaded: (documentCount ?? 0) > 0,    count: documentCount ?? 0 },
      { module: 'auftragseingang', label: 'Auftragseingang',     loaded: (intakeCount ?? 0) > 0,      count: intakeCount ?? 0 },
      { module: 'top-management-demo', label: 'Top-Management-Demo 2026_067', loaded: (topMgmtCount ?? 0) > 0, count: topMgmtCount ?? 0 },
    ],
  }

  return NextResponse.json(status)
}
