import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { sendStatusUpdateToClient } from '@/lib/email'

function checkAdmin(req: NextRequest): boolean {
  const password = req.headers.get('x-admin-password')
  return password === process.env.ADMIN_PASSWORD
}

// GET /api/orders — list all orders (admin only)
export async function GET(req: NextRequest) {
  if (!checkAdmin(req)) {
    return NextResponse.json({ error: 'No autoritzat' }, { status: 401 })
  }

  const { searchParams } = new URL(req.url)
  const format = searchParams.get('format')

  const orders = await prisma.order.findMany({
    orderBy: { createdAt: 'desc' },
  })

  if (format === 'csv') {
    const cols = [
      'orderNumber', 'createdAt', 'status', 'product', 'sizeTshirt', 'sizeSocks',
      'nom', 'cognoms', 'email', 'telefon',
      'shipping', 'adreca', 'codiPostal', 'poblacio', 'provincia',
      'baseAmount', 'shippingAmount', 'totalAmount',
    ]
    const header = cols.join(';')
    const rows = orders.map((o) =>
      cols
        .map((c) => {
          const val = (o as Record<string, unknown>)[c]
          if (val instanceof Date) return val.toISOString().split('T')[0]
          if (typeof val === 'number') return String(val).replace('.', ',')
          return String(val ?? '').replace(/;/g, ',')
        })
        .join(';')
    )
    const csv = [header, ...rows].join('\n')

    return new Response(csv, {
      headers: {
        'Content-Type': 'text/csv; charset=utf-8',
        'Content-Disposition': `attachment; filename="comandes-cc2026-${new Date().toISOString().split('T')[0]}.csv"`,
      },
    })
  }

  return NextResponse.json({ orders })
}

// PATCH /api/orders — update order status
export async function PATCH(req: NextRequest) {
  if (!checkAdmin(req)) {
    return NextResponse.json({ error: 'No autoritzat' }, { status: 401 })
  }

  const { id, status, notes } = await req.json()

  const validStatuses = ['PENDING', 'PAID', 'PREPARING', 'SHIPPED', 'DELIVERED', 'CANCELLED']
  if (!id || !validStatuses.includes(status)) {
    return NextResponse.json({ error: 'Dades no vàlides' }, { status: 400 })
  }

  const order = await prisma.order.update({
    where: { id },
    data: {
      status,
      ...(notes !== undefined ? { notes } : {}),
    },
  })

  // Notify client on key status changes
  if (['SHIPPED', 'DELIVERED', 'PREPARING'].includes(status)) {
    await sendStatusUpdateToClient(order).catch(console.error)
  }

  return NextResponse.json({ order })
}
