import { NextResponse } from 'next/server'
import { getUserSession } from '@/lib/auth/permissions'
import { createAdminClient } from '@/lib/supabase/admin'
import { DEMO_TOP_MGMT_CONSULTANT_ID } from '@/lib/demo/demo-ids'

const DEMO_EMAIL = 'demo.testperson@kadi-demo.internal'

// Single-tenant: demo gate is env-var only. The cp_tenants.demo_enabled
// dual-gate has been removed together with the control-plane layer.
async function requireDemoMode(): Promise<NextResponse | null> {
  if (process.env.DEMO_MODE_ENABLED !== 'true') {
    return NextResponse.json(
      { error: 'demo_mode_disabled', message: 'Demo mode is not enabled in this environment.' },
      { status: 403 },
    )
  }
  return null
}

export async function POST() {
  const demoBlock = await requireDemoMode(); if (demoBlock) return demoBlock
  const session = await getUserSession()
  if (!session || (session.role !== 'admin' && session.role !== 'masteradmin')) {
    return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
  }

  const admin = createAdminClient()

  // Clean up any existing demo rows first. The consultants sweep must exclude
  // the top_management_demo roster row (stable ddd7 id): it is demo-tagged but
  // master data of another pack — and without the exclusion the maybeSingle()
  // below would error on 2 rows once that pack is seeded.
  await admin.from('user_profiles').delete().eq('is_demo', true)
  const { data: demoConsultant } = await admin
    .from('consultants')
    .select('id, auth_user_id')
    .eq('is_demo', true)
    .neq('id', DEMO_TOP_MGMT_CONSULTANT_ID)
    .maybeSingle()
  if (demoConsultant?.auth_user_id) {
    await admin.auth.admin.deleteUser(demoConsultant.auth_user_id).catch(() => null)
  }
  await admin.from('consultants').delete().eq('is_demo', true).neq('id', DEMO_TOP_MGMT_CONSULTANT_ID)

  // Create a real auth user so the profile FK is satisfied
  const { data: authData, error: authError } = await admin.auth.admin.createUser({
    email: DEMO_EMAIL,
    password: 'Demo_Temp_9x!',
    email_confirm: true,
  })
  if (authError || !authData.user) {
    return NextResponse.json({ error: authError?.message ?? 'auth error' }, { status: 500 })
  }
  const authUserId = authData.user.id

  // Fetch lowest-privilege role id
  const { data: roleRow } = await admin
    .from('roles')
    .select('id')
    .eq('code', 'readonly')
    .single()

  // Create demo consultant
  const { data: consultant } = await admin
    .from('consultants')
    .insert({
      first_name:   'Demo',
      last_name:    'Testperson',
      display_name: 'Demo Testperson',
      auth_user_id: authUserId,
      role:         'consultant',
      is_active:    true,
      is_demo:      true,
    })
    .select('id')
    .single()

  // Create demo user profile
  const { data: profile, error: profileError } = await admin
    .from('user_profiles')
    .insert({
      auth_user_id:         authUserId,
      first_name:           'Demo',
      last_name:            'Testperson',
      display_name:         'Demo Testperson',
      email:                DEMO_EMAIL,
      role_id:              roleRow?.id ?? null,
      account_status:       'pending_approval',
      must_change_password: true,
      is_demo:              true,
      created_by:           session.authUserId,
    })
    .select()
    .single()

  if (profileError) {
    await admin.auth.admin.deleteUser(authUserId).catch(() => null)
    return NextResponse.json({ error: profileError.message }, { status: 500 })
  }

  return NextResponse.json({ profile, consultant_id: consultant?.id }, { status: 201 })
}

export async function DELETE() {
  const demoBlock = await requireDemoMode(); if (demoBlock) return demoBlock
  const session = await getUserSession()
  if (!session || (session.role !== 'admin' && session.role !== 'masteradmin')) {
    return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
  }

  const admin = createAdminClient()

  // Find auth_user_id to delete from auth (excluding the top_management_demo
  // roster row — see POST above for why).
  const { data: demoConsultant } = await admin
    .from('consultants')
    .select('auth_user_id')
    .eq('is_demo', true)
    .neq('id', DEMO_TOP_MGMT_CONSULTANT_ID)
    .maybeSingle()

  await admin.from('user_profiles').delete().eq('is_demo', true)
  await admin.from('consultants').delete().eq('is_demo', true).neq('id', DEMO_TOP_MGMT_CONSULTANT_ID)

  if (demoConsultant?.auth_user_id) {
    await admin.auth.admin.deleteUser(demoConsultant.auth_user_id).catch(() => null)
  }

  return NextResponse.json({ success: true })
}

export async function PATCH() {
  // Confirm demo user: set account_status = 'active'
  const demoBlock = await requireDemoMode(); if (demoBlock) return demoBlock
  const session = await getUserSession()
  if (!session || (session.role !== 'admin' && session.role !== 'masteradmin')) {
    return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
  }

  const admin = createAdminClient()
  const { data: updated, error } = await admin
    .from('user_profiles')
    .update({ account_status: 'active' })
    .eq('is_demo', true)
    .select()
    .single()

  if (error) return NextResponse.json({ error: error.message }, { status: 500 })
  return NextResponse.json({ profile: updated })
}
