import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'
import { StatutVente, StatutAtelier } from '@prisma/client'

// POST /api/atelier/seed - Seed sample work order data for testing
export async function POST(request: NextRequest) {
  try {
    // Check if we already have test data
    const existingOrders = await db.vente.count({
      where: {
        statut: StatutVente.PAYEE
      }
    })

    if (existingOrders > 0) {
      return NextResponse.json(
        { 
          message: 'Test data already exists',
          count: existingOrders
        },
        { status: 200 }
      )
    }

    // Get or create sample products
    const frames = await db.produit.findMany({
      where: { categorie: 'MONTURE' },
      take: 3
    })

    const lenses = await db.produit.findMany({
      where: { categorie: 'VERRE' },
      take: 3
    })

    // Get or create a sample client
    let client = await db.client.findFirst()
    if (!client) {
      client = await db.client.create({
        data: {
          nom: 'Dupont',
          prenom: 'Jean',
          email: 'jean.dupont@email.com',
          telephone: '0612345678',
          adresse: '123 Rue de la République',
          ville: 'Paris',
          codePostal: '75001'
        }
      })
    }

    // Create vision measurements for the client
    let patient = await db.patient.findFirst({
      where: { clientId: client.id }
    })

    if (!patient) {
      patient = await db.patient.create({
        data: {
          clientId: client.id,
          odSphere: -2.00,
          odCylindre: -0.50,
          odAxe: 180,
          ogSphere: -1.75,
          ogCylindre: -0.75,
          ogAxe: 175,
          addition: 1.50,
          pd: 63,
          hauteur: 22
        }
      })
    }

    // Create sample sales with different workshop statuses
    const workOrderData = [
      {
        statutAtelier: StatutAtelier.EN_ATTENTE,
        products: [
          frames[0],
          lenses[0]
        ]
      },
      {
        statutAtelier: StatutAtelier.EN_COURS,
        products: [
          frames[1] || frames[0],
          lenses[1] || lenses[0]
        ]
      },
      {
        statutAtelier: StatutAtelier.TERMINE,
        products: [
          frames[2] || frames[0],
          lenses[2] || lenses[0]
        ]
      },
      {
        statutAtelier: StatutAtelier.PRET,
        products: [
          frames[0],
          lenses[1] || lenses[0]
        ]
      }
    ]

    const createdOrders = []

    for (const orderData of workOrderData) {
      const totalHT = orderData.products.reduce((sum, p) => sum + p.prixVenteTTC / 1.2, 0)
      const totalTVA = orderData.products.reduce((sum, p) => sum + p.prixVenteTTC - p.prixVenteTTC / 1.2, 0)
      const totalTTC = orderData.products.reduce((sum, p) => sum + p.prixVenteTTC, 0)

      const order = await db.vente.create({
        data: {
          clientId: client.id,
          numero: `V${new Date().getFullYear()}${String(new Date().getMonth() + 1).padStart(2, '0')}${String(createdOrders.length + 1).padStart(4, '0')}`,
          statut: StatutVente.PAYEE,
          statutAtelier: orderData.statutAtelier,
          montantHT: totalHT,
          montantTVA: totalTVA,
          montantTTC: totalTTC,
          dateAtelier: new Date(),
          lignes: {
            create: orderData.products.map(product => ({
              produitId: product.id,
              quantite: 1,
              prixUnitaireHT: product.prixVenteTTC / 1.2,
              prixUnitaireTTC: product.prixVenteTTC,
              remise: 0,
              montantHT: product.prixVenteTTC / 1.2,
              montantTTC: product.prixVenteTTC
            }))
          },
          paiements: {
            create: {
              mode: 'CARTE',
              montant: totalTTC,
              reference: `TEST${createdOrders.length + 1}`
            }
          }
        },
        include: {
          client: true,
          lignes: {
            include: {
              produit: true
            }
          },
          paiements: true
        }
      })

      createdOrders.push(order)
    }

    return NextResponse.json({
      message: 'Sample work order data created successfully',
      count: createdOrders.length,
      orders: createdOrders.map(o => ({
        id: o.id,
        numero: o.numero,
        statutAtelier: o.statutAtelier
      }))
    })
  } catch (error) {
    console.error('Error seeding work order data:', error)
    return NextResponse.json(
      { error: 'Failed to seed work order data', details: error instanceof Error ? error.message : 'Unknown error' },
      { status: 500 }
    )
  }
}
