// tdd-guard:skip — v1 API route handler; covered by API-route tests (Batch 6), not a unit sibling.
import { createClient } from '@/lib/supabase/server'
import { ok, list, badRequest, unauthorized, serverError, readPagination } from '@/lib/api'
import { OEE_RECORDS_CONFLICT_TARGET } from '@/lib/oee/constants'

export async function GET(request: Request) {
  const supabase = await createClient()
  const { data: claimsData } = await supabase.auth.getClaims()
  if (!claimsData?.claims) return unauthorized()

  const { searchParams } = new URL(request.url)
  const { page, limit, offset } = readPagination(searchParams)
  const line = searchParams.get('line')
  const year = searchParams.get('year')
  const weekFrom = searchParams.get('week_from')
  const weekTo = searchParams.get('week_to')

  let query = supabase
    .from('oee_records')
    .select('*', { count: 'exact' })
    .order('year', { ascending: false })
    .order('calendar_week', { ascending: false })
    .range(offset, offset + limit - 1)

  if (line) query = query.ilike('line_name', `%${line}%`)
  if (year) query = query.eq('year', parseInt(year, 10))
  if (weekFrom) query = query.gte('calendar_week', parseInt(weekFrom, 10))
  if (weekTo) query = query.lte('calendar_week', parseInt(weekTo, 10))

  const { data, error, count } = await query
  if (error) return serverError(error.message)

  return list(data ?? [], { page, limit, total: count ?? 0 })
}

export async function POST(request: Request) {
  const supabase = await createClient()
  const { data: claimsData } = await supabase.auth.getClaims()
  if (!claimsData?.claims) return unauthorized()

  const body = await request.json()
  // Client/iOS contract keeps `week_number` in the request body; the DB column
  // is `calendar_week`. Map on write so the API contract stays stable.
  const { line_name, year, week_number, ...rest } = body

  if (!line_name || year === undefined || week_number === undefined) {
    return badRequest('line_name, year, and week_number are required')
  }

  // Upsert (not insert) so a repeat write for the same line/week is idempotent —
  // matching the web OEE calculator — instead of failing the project-scoped unique
  // constraint and risking iOS/web duplicates (KAR-704 O8).
  const { data, error } = await supabase
    .from('oee_records')
    .upsert({ ...rest, line_name, year, calendar_week: week_number }, {
      onConflict: OEE_RECORDS_CONFLICT_TARGET,
    })
    .select()
    .single()

  if (error) return serverError(error.message)

  return ok(data, { status: 201 })
}
