import { NextResponse } from 'next/server';
import prisma from '../../../lib/prisma';
import { getServerSession } from "next-auth/next";
import { authOptions } from "../auth/[...nextauth]/route";
import { writeFile, mkdir } from 'fs/promises';
import path from 'path';

async function checkPerm(perm: string) {
  const session = await getServerSession(authOptions);
  const perms = (session?.user as any)?.permissions || [];
  return perms.includes(perm);
}

export async function GET() {
  try {
    const products = await prisma.product.findMany({ orderBy: { name: 'asc' } });
    return NextResponse.json(products);
  } catch (error) {
    return NextResponse.json({ error: 'Ladefehler' }, { status: 500 });
  }
}

export async function POST(request: Request) {
  if (!await checkPerm('PURCHASING_MANAGE')) return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 });

  try {
    const formData = await request.formData();
    const name = formData.get('name') as string;
    const description = formData.get('description') as string || '';
    const sku = formData.get('sku') as string || null;
    const purchasePrice = parseFloat(formData.get('purchasePrice') as string || '0');
    const salePrice = parseFloat(formData.get('salePrice') as string || '0');
    const stock = parseInt(formData.get('stock') as string || '0');
    const unit = formData.get('unit') as string || 'Stk';
    const category = formData.get('category') as string || null;
    const trackStock = formData.get('trackStock') !== 'false';
    const image = formData.get('image') as File | null;

    let imagePath = null;
    if (image && image.size > 0) {
      const uploadDir = path.join(process.cwd(), 'uploads', 'products');
      await mkdir(uploadDir, { recursive: true });
      const ext = image.name.split('.').pop();
      const savedName = `prod_${Date.now()}.${ext}`;
      const buffer = Buffer.from(await image.arrayBuffer());
      await writeFile(path.join(uploadDir, savedName), buffer);
      imagePath = `/api/products/image/${savedName}`;
    }

    const product = await prisma.product.create({
      data: { name, description, sku, purchasePrice, salePrice, stock, unit, category, trackStock, imagePath }
    });

    return NextResponse.json(product, { status: 201 });
  } catch (error: any) {
    if (error.code === 'P2002') return NextResponse.json({ error: 'Artikelnummer existiert bereits' }, { status: 400 });
    console.error(error);
    return NextResponse.json({ error: 'Fehler beim Erstellen' }, { status: 500 });
  }
}

export async function PUT(request: Request) {
  if (!await checkPerm('PURCHASING_MANAGE')) return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 });

  try {
    const formData = await request.formData();
    const id = parseInt(formData.get('id') as string);
    const data: any = {
      name: formData.get('name') as string,
      description: formData.get('description') as string || '',
      sku: formData.get('sku') as string || null,
      purchasePrice: parseFloat(formData.get('purchasePrice') as string || '0'),
      salePrice: parseFloat(formData.get('salePrice') as string || '0'),
      stock: parseInt(formData.get('stock') as string || '0'),
      unit: formData.get('unit') as string || 'Stk',
      category: formData.get('category') as string || null,
      active: formData.get('active') === 'true',
      trackStock: formData.get('trackStock') !== 'false',
    };

    const image = formData.get('image') as File | null;
    if (image && image.size > 0) {
      const uploadDir = path.join(process.cwd(), 'uploads', 'products');
      await mkdir(uploadDir, { recursive: true });
      const ext = image.name.split('.').pop();
      const savedName = `prod_${Date.now()}.${ext}`;
      const buffer = Buffer.from(await image.arrayBuffer());
      await writeFile(path.join(uploadDir, savedName), buffer);
      data.imagePath = `/api/products/image/${savedName}`;
    }

    const product = await prisma.product.update({ where: { id }, data });
    return NextResponse.json(product);
  } catch (error: any) {
    if (error.code === 'P2002') return NextResponse.json({ error: 'Artikelnummer existiert bereits' }, { status: 400 });
    console.error(error);
    return NextResponse.json({ error: 'Fehler beim Aktualisieren' }, { status: 500 });
  }
}

export async function DELETE(request: Request) {
  if (!await checkPerm('PURCHASING_MANAGE')) return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 });
  try {
    const { searchParams } = new URL(request.url);
    const id = parseInt(searchParams.get('id') || '0');
    await prisma.product.delete({ where: { id } });
    return NextResponse.json({ success: true });
  } catch (error) {
    return NextResponse.json({ error: 'Löschen fehlgeschlagen' }, { status: 500 });
  }
}
