// tdd-guard:skip — Next.js route handler; testable logic lives in lib/api/error.ts + lib/api/schemas.ts tests.
import { NextRequest, NextResponse } from 'next/server'
import { createClient } from '@/lib/supabase/server'
import { getUserSession, hasPermission } from '@/lib/auth/permissions'
import { routeError, apiError } from '@/lib/api/error'
import { CreateValueStreamMapBody } from '@/lib/api/schemas'

export async function GET() {
  try {
  } catch (e) {
    if (e instanceof Response) return e
    throw e
  }

  // Permissions-Enforcement (Wertstrom P0, KAR-878): vsm.read/vsm.write
  // existierten in der DB (supabase-migration-oee-vsm-permissions.sql),
  // wurden aber nirgends geprüft — diese Route nutzte nur getClaims()
  // (reine Authentifizierung, keine Autorisierung).
  const session = await getUserSession()
  if (!session) return apiError.unauthorized()
  if (!hasPermission(session, 'vsm.read')) return apiError.forbidden()

  const supabase = await createClient()
  const { data, error } = await supabase
    .from('value_stream_maps')
    .select('id, title, description, project_id, created_by, created_at, updated_at')
    .order('updated_at', { ascending: false })

  if (error) return routeError('Wertstrom-Karten konnten nicht geladen werden.', error)
  return NextResponse.json(data)
}

export async function POST(req: NextRequest) {
  try {
  } catch (e) {
    if (e instanceof Response) return e
    throw e
  }

  const session = await getUserSession()
  if (!session) return apiError.unauthorized()
  if (!hasPermission(session, 'vsm.write')) return apiError.forbidden()

  // Wertstrom P0 (KAR-878): was a plain `as` cast with zero runtime
  // validation — title is required non-empty, description/project_id
  // tolerant of null/absent (see lib/api/schemas.ts CreateValueStreamMapBody).
  const parsed = CreateValueStreamMapBody.safeParse(await req.json().catch(() => ({})))
  if (!parsed.success) return apiError.invalidBody(parsed.error.issues)
  const body = parsed.data

  const supabase = await createClient()

  // Ownership check (Review-Fix, adversarial review PR #360, C6 Beifang):
  // body.project_id was only format-validated (uuid) — the same gap the
  // SimVSM confirm route had (see app/api/wertstrom/import/confirm/route.ts
  // for the full RLS/vsm_own reasoning). Same "0 rows = not found" IDOR
  // discipline as app/project/[id]/export/actions.ts.
  if (body.project_id) {
    const { data: project, error: projectErr } = await supabase.from('projects').select('id').eq('id', body.project_id).maybeSingle()
    if (projectErr) return routeError('Projekt konnte nicht geprüft werden.', projectErr)
    if (!project) return apiError.invalidBody([{ message: 'Projekt nicht gefunden oder kein Zugriff.' }])
  }

  const { data, error } = await supabase
    .from('value_stream_maps')
    .insert({
      title: body.title,
      description: body.description ?? null,
      project_id: body.project_id ?? null,
      created_by: session.authUserId,
    })
    .select()
    .single()

  if (error) return routeError('Wertstrom-Karte konnte nicht erstellt werden.', error)
  return NextResponse.json(data, { status: 201 })
}
