export const dynamic = "force-dynamic";
import getDb from '@/lib/db';
import { generateToken } from '@/lib/auth';
import bcrypt from 'bcryptjs';

// POST /api/auth/login - 用户登录
export async function POST(request) {
  try {
    const { username, password } = await request.json();

    if (!username || !password) {
      return Response.json(
        { error: '用户名和密码不能为空' },
        { status: 400 }
      );
    }

    const db = await getDb();

    // 查找用户
    const user = db.prepare('SELECT * FROM users WHERE username = ?').get(username);
    if (!user) {
      return Response.json(
        { error: '用户名或密码错误' },
        { status: 401 }
      );
    }

    if (user.status !== 1) {
      return Response.json(
        { error: '该账户已被停用，禁止登录' },
        { status: 403 }
      );
    }

    // 验证密码
    const isValid = bcrypt.compareSync(password, user.password);
    if (!isValid) {
      return Response.json(
        { error: '用户名或密码错误' },
        { status: 401 }
      );
    }

    // 生成 token
    const token = generateToken(user);

    // 获取用户信息（不含密码）
    const { password: _, ...userInfo } = user;

    // 获取部门名称
    if (user.department_id) {
      const dept = db.prepare('SELECT name FROM departments WHERE id = ?').get(user.department_id);
      if (dept) {
        userInfo.department_name = dept.name;
      }
    }

    // 获取系统配置（登录页面展示用）
    const configs = db.prepare('SELECT config_key, config_value FROM system_config').all();
    const system_config = {};
    for (const config of configs) {
      system_config[config.config_key] = config.config_value;
    }

    return Response.json({
      token,
      user: userInfo,
      system_config,
    });
  } catch (error) {
    console.error('登录失败:', error);
    return Response.json(
      { error: '服务器内部错误' },
      { status: 500 }
    );
  }
}
