'use server';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { updatePfpUrl, getPfpUrl, getUser } from '~/server/functions';
import { middleware } from '~/middleware';
import fs from 'fs/promises';
import path from 'path';
import type { User } from '~/server/types';

const UPLOAD_DIR = path.join(process.cwd(), `public/${process.env.UPLOAD_DIR}`);

export const POST = async (request: NextRequest) => {
  const middlewareResponse = await middleware(request);
  if (middlewareResponse) {
    console.log('Middleware rejected the request');
    return middlewareResponse;
  }
  try {
    const formData = await request.formData();
    const file = formData.get('file') as File | null;
    const userId = formData.get('userId') as number | null;
    if (!file || !userId)
      return NextResponse.json({ message: 'Missing file or userId' }, { status: 400 });
    if (!file.type.startsWith('image/'))
      return NextResponse.json({ message: 'Invalid file type' }, { status: 400 });
    await fs.mkdir(UPLOAD_DIR, { recursive: true });

    // Generate name for the uploaded file
    const fileExtension = path.extname(file.name);
    const fileName = `${userId}_${Date.now()}${fileExtension}`;
    const filePath = path.join(UPLOAD_DIR, fileName);

    // Write the file to the upload directory
    const buffer = Buffer.from(await file.arrayBuffer());
    await fs.writeFile(filePath, buffer);
    const pfpUrl = `/${process.env.UPLOAD_DIR}/${fileName}`;

    // Delete the old pfp file if it exists
    const oldPfpUrl = await getPfpUrl(userId);
    console.log("Old pfp url: ", oldPfpUrl);
    if (oldPfpUrl) {
      const oldFilePath = path.join(process.cwd(), 'public', oldPfpUrl);
      await fs.unlink(oldFilePath).catch((error) => {
        console.error('Error deleting old pfp file:', error);
      });
    } else {
      console.log('No old pfp file found');
    }
    // Update the pfpUrl in the database
    const result = await updatePfpUrl(userId, pfpUrl);
    if (!result) {
      console.log('Error updating pfp url in database');
      return NextResponse.json({ message: 'Error updating pfp url in database' }, { status: 500 });
    }
    // Get the updated user
    const user: User | null = await getUser(userId);
    if (!user) {
      console.log('Error getting user from database');
      return NextResponse.json({ message: 'Error getting user from database' }, { status: 500 });
    }
    // Return the updated user
    return NextResponse.json(user);

  } catch (error) {
    console.error('Error updating pfp:', error);
    if (error instanceof Error) {
      return NextResponse.json({ message: error.message }, { status: 500 });
    } else {
      return NextResponse.json({ message: 'Unknown error occurred' }, { status: 500 });
    }
  }
};
