import { createResponse, handleApiError } from '@/src/lib/api';
import { NextRequest } from 'next/server';
import { getSession } from '@/lib/auth';
import { supabase } from '@/src/lib/supabase';

export async function POST(req: NextRequest) {
  try {
    const formData = await req.formData();
    const file = formData.get('file') as File;

    const session = await getSession();

    if (!file || !session?.user.id) {
      return createResponse(400, 'Missing file or userId');
    }

    const fileExt = file.name.split('.').pop();
    const filePath = `${session.user.id}/${Math.random()}.${fileExt}`;
    const { error } = await supabase.storage.from('images').upload(filePath, file, {
      upsert: true,
    });
    if (error) throw error;

    const {
      data: { publicUrl },
    } = supabase.storage.from('images').getPublicUrl(filePath);

    return createResponse(200, 'Image uploaded successfully', {
      data: {
        publicUrl,
      },
    });
  } catch (error) {
    return handleApiError(error);
  }
}
