export const dynamic = 'force-dynamic';
export const revalidate = 0;
export const runtime = 'nodejs';

import { NextRequest, NextResponse } from "next/server";
import { createRouteHandlerClient } from "@supabase/auth-helpers-nextjs";
import { cookies } from "next/headers";
import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";

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 GET(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 });
    }

    const { searchParams } = new URL(req.url);
    const orgId = searchParams.get('org_id');
    const category = searchParams.get('category');

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

    // Récupérer les documents depuis Supabase
    let query = sb
      .from('documents')
      .select('*')
      .eq('org_id', orgId)
      .eq('category', category)
      .order('date_added', { ascending: false });

    const { data: documents, error } = await query;

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

    // Générer les URLs présignées pour chaque document
    const documentsWithUrls = await Promise.all(
      (documents || []).map(async (doc) => {
        if (doc.storage_path) {
          try {
            const command = new GetObjectCommand({
              Bucket: BUCKET_NAME,
              Key: doc.storage_path,
            });
            const url = await getSignedUrl(s3Client, command, { expiresIn: 3600 });
            return { ...doc, download_url: url };
          } catch (err) {
            console.error(`Erreur génération URL pour ${doc.storage_path}:`, err);
            return doc;
          }
        }
        return doc;
      })
    );

    return NextResponse.json({ documents: documentsWithUrls });

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