export const dynamic = "force-dynamic";
import getDb from '@/lib/db';
import { getUserFromRequest, unauthorizedResponse, forbiddenResponse, checkRole } from '@/lib/auth';

// GET /api/departments - 获取所有部门列表
export async function GET(request) {
  try {
    const user = getUserFromRequest(request);
    if (!user) return unauthorizedResponse();

    const db = await getDb();
    const departments = db.prepare('SELECT * FROM departments ORDER BY id ASC').all();

    return Response.json(departments);
  } catch (error) {
    console.error('获取部门列表失败:', error);
    return Response.json(
      { error: '服务器内部错误' },
      { status: 500 }
    );
  }
}

// POST /api/departments - 创建部门（仅管理员）
export async function POST(request) {
  try {
    const user = getUserFromRequest(request);
    if (!user) return unauthorizedResponse();
    if (!checkRole(user, ['admin'])) return forbiddenResponse();

    const { name } = await request.json();

    if (!name || !name.trim()) {
      return Response.json(
        { error: '部门名称不能为空' },
        { status: 400 }
      );
    }

    const db = await getDb();

    // 检查部门名是否重复
    const existing = db.prepare('SELECT id FROM departments WHERE name = ?').get(name.trim());
    if (existing) {
      return Response.json(
        { error: '部门名称已存在' },
        { status: 400 }
      );
    }

    const result = db.prepare('INSERT INTO departments (name) VALUES (?)').run(name.trim());

    const department = db.prepare('SELECT * FROM departments WHERE id = ?').get(result.lastInsertRowid);

    return Response.json(department, { status: 201 });
  } catch (error) {
    console.error('创建部门失败:', error);
    return Response.json(
      { error: '服务器内部错误' },
      { status: 500 }
    );
  }
}
