import { NextRequest, NextResponse } from "next/server";
import { createRouteHandlerClient } from "@supabase/auth-helpers-nextjs";
import { cookies } from "next/headers";
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
import { v4 as uuidv4 } from 'uuid';

const s3Client = new S3Client({
  region: process.env.AWS_REGION || "eu-west-3",
  credentials: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID || "",
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY || "",
  },
});

const BUCKET_NAME = (process.env.AWS_S3_BUCKET || "odentas-docs").trim();

export async function POST(req: NextRequest) {
  try {
    const sb = createRouteHandlerClient({ cookies });
    
    // Vérifier que l'utilisateur est staff
    const { data: { user } } = await sb.auth.getUser();
    if (!user) {
      return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
    }

    const { data: staffUser } = await sb
      .from("staff_users")
      .select("is_staff")
      .eq("user_id", user.id)
      .single();

    if (!staffUser?.is_staff) {
      return NextResponse.json({ error: "Accès refusé" }, { status: 403 });
    }

    // Parser le form data
    const formData = await req.formData();
    const file = formData.get('file') as File;
    const orgId = formData.get('org_id') as string;
    const orgKey = formData.get('org_key') as string;
    const category = formData.get('category') as string;
    const docType = formData.get('doc_type') as string | null;
    const period = formData.get('period') as string | null;

    if (!file || !orgId || !orgKey || !category) {
      return NextResponse.json({ error: "Paramètres manquants" }, { status: 400 });
    }

    // Générer le path S3
    let s3Key: string;
    let filename: string;

    if (category === 'docs_generaux') {
      // Documents généraux: documents/{org_key}/docs-generaux/{doc_type}_{uuid}.pdf
      if (!docType) {
        return NextResponse.json({ error: "doc_type requis pour docs_generaux" }, { status: 400 });
      }
      const uniqueId = uuidv4().replace(/-/g, '').substring(0, 16);
      filename = `${docType}_${uniqueId}.pdf`;
      s3Key = `documents/${orgKey}/docs-generaux/${filename}`;
    } else if (category === 'docs_comptables') {
      // Documents comptables: documents/{org_key}/docs_comptables/{period}/{filename}
      if (!period) {
        return NextResponse.json({ error: "period requis pour docs_comptables" }, { status: 400 });
      }
      filename = file.name;
      s3Key = `documents/${orgKey}/docs_comptables/${period}/${filename}`;
    } else {
      return NextResponse.json({ error: "Catégorie invalide" }, { status: 400 });
    }

    // Upload vers S3
    const buffer = Buffer.from(await file.arrayBuffer());
    const uploadCommand = new PutObjectCommand({
      Bucket: BUCKET_NAME,
      Key: s3Key,
      Body: buffer,
      ContentType: file.type,
    });

    await s3Client.send(uploadCommand);

    // Créer l'entrée dans Supabase
    const { error: insertError } = await sb
      .from('documents')
      .insert({
        org_id: orgId,
        category: category,
        type_label: docType || 'Document',
        filename: filename,
        storage_path: s3Key,
        size_bytes: file.size,
        period_label: period,
        date_added: new Date().toISOString(),
      });

    if (insertError) {
      console.error('Erreur insertion Supabase:', insertError);
      return NextResponse.json({ error: "Erreur base de données" }, { status: 500 });
    }

    return NextResponse.json({ 
      success: true,
      filename,
      s3Key 
    });

  } catch (error) {
    console.error("Erreur upload document:", error);
    return NextResponse.json(
      { error: "Erreur serveur" },
      { status: 500 }
    );
  }
}
