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

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

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

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

    const db = await getDb();

    // 检查部门是否存在
    const dept = db.prepare('SELECT id FROM departments WHERE id = ?').get(id);
    if (!dept) {
      return Response.json(
        { error: '部门不存在' },
        { status: 404 }
      );
    }

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

    db.prepare('UPDATE departments SET name = ? WHERE id = ?').run(name.trim(), id);

    const updated = db.prepare('SELECT * FROM departments WHERE id = ?').get(id);
    return Response.json(updated);
  } catch (error) {
    console.error('更新部门失败:', error);
    return Response.json(
      { error: '服务器内部错误' },
      { status: 500 }
    );
  }
}

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

    const { id } = await params;
    const db = await getDb();

    // 检查部门是否存在
    const dept = db.prepare('SELECT id FROM departments WHERE id = ?').get(id);
    if (!dept) {
      return Response.json(
        { error: '部门不存在' },
        { status: 404 }
      );
    }

    // 使用事务：解除关联并删除部门
    const deleteTx = db.transaction(() => {
      // 1. 将该部门下的用户的 department_id 设为 null
      db.prepare('UPDATE users SET department_id = NULL WHERE department_id = ?').run(id);
      
      // 2. 将该部门下的合同的 department_id 设为 null (保留 department_name 做历史记录)
      db.prepare('UPDATE contracts SET department_id = NULL WHERE department_id = ?').run(id);
      
      // 3. 删除部门
      db.prepare('DELETE FROM departments WHERE id = ?').run(id);
    });

    deleteTx();

    return Response.json({ message: '删除成功' });
  } catch (error) {
    console.error('删除部门失败:', error);
    return Response.json(
      { error: '服务器内部错误' },
      { status: 500 }
    );
  }
}
