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

// GET /api/contracts - 获取合同列表（带筛选和分页）
export async function GET(request) {
  try {
    const user = getUserFromRequest(request);
    if (!user) return unauthorizedResponse();

    const { searchParams } = new URL(request.url);
    const status = searchParams.get('status');
    const search = searchParams.get('search');
    const date_from = searchParams.get('date_from');
    const date_to = searchParams.get('date_to');
    const department_id = searchParams.get('department_id');
    const page = parseInt(searchParams.get('page') || '1', 10);
    const page_size = parseInt(searchParams.get('page_size') || '10', 10);

    const db = await getDb();

    let whereClauses = [];
    let queryParams = [];

    // 根据角色应用可见性规则
    switch (user.role) {
      case 'employee':
        // 员工只能看到自己创建的合同
        whereClauses.push('c.creator_id = ?');
        queryParams.push(user.id);
        break;
      case 'supervisor':
        // 主管只能看到本部门的合同
        whereClauses.push('c.department_id = ?');
        queryParams.push(user.department_id);
        break;
      case 'finance':
      case 'secretary':
      case 'admin':
        // 财务、秘书长、管理员可以看到所有合同
        break;
    }

    // 状态筛选
    if (status && status !== 'all') {
      whereClauses.push('c.status = ?');
      queryParams.push(status);
    }

    // 搜索筛选（项目名称、合作单位名称）
    if (search && search.trim()) {
      whereClauses.push('(c.project_name LIKE ? OR c.partner_name LIKE ?)');
      const keyword = `%${search.trim()}%`;
      queryParams.push(keyword, keyword);
    }

    // 日期范围筛选
    if (date_from) {
      whereClauses.push('c.sign_date >= ?');
      queryParams.push(date_from);
    }
    if (date_to) {
      whereClauses.push('c.sign_date <= ?');
      queryParams.push(date_to);
    }

    // 部门筛选
    if (department_id) {
      whereClauses.push('c.department_id = ?');
      queryParams.push(department_id);
    }

    const whereSQL = whereClauses.length > 0 ? `WHERE ${whereClauses.join(' AND ')}` : '';

    // 获取总数
    const countRow = db.prepare(
      `SELECT COUNT(*) as total FROM contracts c ${whereSQL}`
    ).get(...queryParams);
    const total = countRow.total;

    // 获取分页数据
    const offset = (page - 1) * page_size;
    const contracts = db.prepare(
      `SELECT c.*, p.name as partner_name
       FROM contracts c
       LEFT JOIN partners p ON c.partner_id = p.id
       ${whereSQL}
       ORDER BY c.created_at DESC
       LIMIT ? OFFSET ?`
    ).all(...queryParams, page_size, offset);

    return Response.json({
      contracts,
      data: contracts,
      total,
      page,
      page_size,
    });
  } catch (error) {
    console.error('获取合同列表失败:', error);
    return Response.json(
      { error: '服务器内部错误' },
      { status: 500 }
    );
  }
}

// POST /api/contracts - 创建合同（仅员工可创建）
export async function POST(request) {
  try {
    const user = getUserFromRequest(request);
    if (!user) return unauthorizedResponse();
    if (!checkRole(user, ['employee'])) {
      return forbiddenResponse();
    }

    const body = await request.json();
    const {
      project_name, partner_id, contract_content, contract_years,
      contract_amount, estimated_profit, payment_type, sign_date, project_leader,
    } = body;

    if (!project_name || !partner_id) {
      return Response.json(
        { error: '项目名称和合作单位不能为空' },
        { status: 400 }
      );
    }

    const db = await getDb();

    // 获取用户完整信息（包含部门）
    const fullUser = db.prepare(
      `SELECT u.*, d.name as department_name 
       FROM users u 
       LEFT JOIN departments d ON u.department_id = d.id 
       WHERE u.id = ?`
    ).get(user.id);

    // 查找合作单位名称
    const partner = db.prepare('SELECT name FROM partners WHERE id = ? AND is_deleted = 0').get(partner_id);
    if (!partner) {
      return Response.json(
        { error: '合作单位不存在' },
        { status: 400 }
      );
    }

    const result = db.prepare(`
      INSERT INTO contracts (
        project_name, partner_id, partner_name, contract_content, contract_years,
        contract_amount, estimated_profit, payment_type, sign_date,
        creator_id, creator_name, department_id, department_name, project_leader,
        status
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending_supervisor')
    `).run(
      project_name,
      partner_id,
      partner.name,
      contract_content || null,
      contract_years || null,
      contract_amount || 0,
      estimated_profit !== undefined && estimated_profit !== null ? estimated_profit : null,
      payment_type || 'receive',
      sign_date || null,
      fullUser.id,
      fullUser.real_name,
      fullUser.department_id,
      fullUser.department_name || null,
      project_leader || null
    );

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

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