// tdd-guard:skip — Next.js route handler; testable logic lives in lib/api/error.ts tests.
import { NextRequest, NextResponse } from 'next/server'
import { getUserSession } from '@/lib/auth/permissions'
import { isAtLeastRole } from '@/lib/auth/permissions-shared'
import { routeError } from '@/lib/api/error'
import { createAdminClient } from '@/lib/supabase/admin'

// GET /api/planning/settings
// Returns { calendar_colors?: object, custom_holidays?: object[] }
export async function GET() {
  try {
  } catch (e) {
    if (e instanceof Response) return e
    throw e
  }

  const admin = createAdminClient()
  const { data } = await admin
    .from('app_settings')
    .select('key, value')
    .in('key', ['calendar_colors', 'custom_holidays'])

  const result: Record<string, unknown> = {}
  for (const row of data ?? []) {
    result[row.key as string] = row.value
  }
  return NextResponse.json(result)
}

// PATCH /api/planning/settings
// body: { key: string, value: unknown }
export async function PATCH(req: NextRequest) {
  try {
  } catch (e) {
    if (e instanceof Response) return e
    throw e
  }

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

  const { key, value } = await req.json().catch(() => ({})) as { key?: string; value?: unknown }
  if (!key) return NextResponse.json({ error: 'Missing key' }, { status: 400 })

  const admin = createAdminClient()
  const { error } = await admin.from('app_settings').upsert(
    {
      key,
      value,
      updated_by: session.authUserId,
      updated_at: new Date().toISOString(),
    },
    { onConflict: 'key' },
  )

  if (error) return routeError('Einstellungen konnten nicht gespeichert werden.', error)
  return NextResponse.json({ ok: true })
}
