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

// POST /api/contracts/[id]/approve - 审批合同
export async function POST(request, { params }) {
  try {
    const user = getUserFromRequest(request);
    if (!user) return unauthorizedResponse();

    const { id } = await params;
    const { approved, opinion } = await request.json();

    if (typeof approved !== 'boolean') {
      return Response.json(
        { error: '请指定审批结果' },
        { status: 400 }
      );
    }

    const db = await getDb();

    const contract = db.prepare('SELECT * FROM contracts WHERE id = ?').get(id);
    if (!contract) {
      return Response.json(
        { error: '合同不存在' },
        { status: 404 }
      );
    }

    // 获取审批人完整信息
    const approver = db.prepare('SELECT * FROM users WHERE id = ?').get(user.id);

    const currentStatus = contract.status;

    // 根据当前状态判断权限和下一步操作
    switch (currentStatus) {
      case 'pending_supervisor': {
        // 只有同部门的主管可以审批
        if (user.role !== 'supervisor') {
          return Response.json(
            { error: '只有主管可以进行初审' },
            { status: 403 }
          );
        }
        if (user.department_id !== contract.department_id) {
          return Response.json(
            { error: '只能审批本部门的合同' },
            { status: 403 }
          );
        }

        if (approved) {
          db.prepare(`
            UPDATE contracts SET
              status = 'pending_finance',
              supervisor_opinion = ?,
              supervisor_approved = 1,
              supervisor_id = ?,
              supervisor_name = ?,
              supervisor_time = CURRENT_TIMESTAMP,
              updated_at = CURRENT_TIMESTAMP
            WHERE id = ?
          `).run(opinion || '同意', approver.id, approver.real_name, id);
        } else {
          db.prepare(`
            UPDATE contracts SET
              status = 'rejected',
              supervisor_opinion = ?,
              supervisor_approved = 0,
              supervisor_id = ?,
              supervisor_name = ?,
              supervisor_time = CURRENT_TIMESTAMP,
              reject_reason = ?,
              updated_at = CURRENT_TIMESTAMP
            WHERE id = ?
          `).run(opinion || '不同意', approver.id, approver.real_name, opinion || '主管驳回', id);
        }
        break;
      }

      case 'pending_finance': {
        // 只有财务角色可以审批
        if (user.role !== 'finance') {
          return Response.json(
            { error: '只有财务人员可以进行财务审批' },
            { status: 403 }
          );
        }

        if (approved) {
          db.prepare(`
            UPDATE contracts SET
              status = 'pending_secretary',
              finance_opinion = ?,
              finance_approved = 1,
              finance_id = ?,
              finance_name = ?,
              finance_time = CURRENT_TIMESTAMP,
              updated_at = CURRENT_TIMESTAMP
            WHERE id = ?
          `).run(opinion || '同意', approver.id, approver.real_name, id);
        } else {
          db.prepare(`
            UPDATE contracts SET
              status = 'rejected',
              finance_opinion = ?,
              finance_approved = 0,
              finance_id = ?,
              finance_name = ?,
              finance_time = CURRENT_TIMESTAMP,
              reject_reason = ?,
              updated_at = CURRENT_TIMESTAMP
            WHERE id = ?
          `).run(opinion || '不同意', approver.id, approver.real_name, opinion || '财务驳回', id);
        }
        break;
      }

      case 'pending_secretary': {
        // 只有秘书长角色可以审批
        if (user.role !== 'secretary') {
          return Response.json(
            { error: '只有秘书长可以进行终审' },
            { status: 403 }
          );
        }

        if (approved) {
          db.prepare(`
            UPDATE contracts SET
              status = 'approved',
              secretary_opinion = ?,
              secretary_approved = 1,
              secretary_id = ?,
              secretary_name = ?,
              secretary_time = CURRENT_TIMESTAMP,
              updated_at = CURRENT_TIMESTAMP
            WHERE id = ?
          `).run(opinion || '同意', approver.id, approver.real_name, id);
        } else {
          db.prepare(`
            UPDATE contracts SET
              status = 'rejected',
              secretary_opinion = ?,
              secretary_approved = 0,
              secretary_id = ?,
              secretary_name = ?,
              secretary_time = CURRENT_TIMESTAMP,
              reject_reason = ?,
              updated_at = CURRENT_TIMESTAMP
            WHERE id = ?
          `).run(opinion || '不同意', approver.id, approver.real_name, opinion || '秘书长驳回', id);
        }
        break;
      }

      default:
        return Response.json(
          { error: `当前合同状态 (${currentStatus}) 不允许审批操作` },
          { status: 400 }
        );
    }

    // 返回更新后的合同
    const updated = db.prepare('SELECT * FROM contracts WHERE id = ?').get(id);
    return Response.json(updated);
  } catch (error) {
    console.error('审批合同失败:', error);
    return Response.json(
      { error: '服务器内部错误' },
      { status: 500 }
    );
  }
}
