export const dynamic = "force-dynamic";
import { getUserFromRequest, unauthorizedResponse, forbiddenResponse, checkRole } from '@/lib/auth';
import { v4 as uuidv4 } from 'uuid';
import path from 'path';
import fs from 'fs';

// POST /api/config/logo - 上传公司 Logo（仅管理员）
export async function POST(request) {
  try {
    const user = getUserFromRequest(request);
    if (!user) return unauthorizedResponse();
    if (!checkRole(user, ['admin'])) return forbiddenResponse();

    const formData = await request.formData();
    const file = formData.get('file');

    if (!file) {
      return Response.json(
        { error: '请选择要上传的文件' },
        { status: 400 }
      );
    }

    // 确保上传目录存在
    const uploadDir = path.join(process.cwd(), 'public', 'uploads');
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }

    // 生成唯一文件名
    const ext = path.extname(file.name) || '.png';
    const fileName = `logo_${uuidv4()}${ext}`;
    const filePath = path.join(uploadDir, fileName);

    // 保存文件
    const buffer = Buffer.from(await file.arrayBuffer());
    fs.writeFileSync(filePath, buffer);

    // 返回文件路径（相对于 public 的路径）
    const publicPath = `/uploads/${fileName}`;

    return Response.json({
      path: publicPath,
      fileName: file.name,
    });
  } catch (error) {
    console.error('上传 Logo 失败:', error);
    return Response.json(
      { error: '服务器内部错误' },
      { status: 500 }
    );
  }
}
