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

function buildOpinions(contract) {
  const opinions = [];
  if (contract.supervisor_approved === 1 || contract.supervisor_approved === 0) {
    opinions.push({
      approver_name: contract.supervisor_name || '主管',
      role: 'supervisor',
      created_at: contract.supervisor_time,
      approved: contract.supervisor_approved === 1,
      opinion: contract.supervisor_opinion
    });
  }
  if (contract.finance_approved === 1 || contract.finance_approved === 0) {
    opinions.push({
      approver_name: contract.finance_name || '财务',
      role: 'finance',
      created_at: contract.finance_time,
      approved: contract.finance_approved === 1,
      opinion: contract.finance_opinion
    });
  }
  if (contract.secretary_approved === 1 || contract.secretary_approved === 0) {
    opinions.push({
      approver_name: contract.secretary_name || '秘书长',
      role: 'secretary',
      created_at: contract.secretary_time,
      approved: contract.secretary_approved === 1,
      opinion: contract.secretary_opinion
    });
  }
  return opinions;
}

// GET /api/contracts/[id] - 获取单个合同详情（含附件）
export async function GET(request, { params }) {
  try {
    const user = getUserFromRequest(request);
    if (!user) return unauthorizedResponse();

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

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

    // 获取附件
    const attachments = db.prepare(
      'SELECT * FROM contract_attachments WHERE contract_id = ? ORDER BY created_at DESC'
    ).all(id);

    return Response.json({
      ...contract,
      attachments,
      opinions: buildOpinions(contract),
    });
  } catch (error) {
    console.error('获取合同详情失败:', error);
    return Response.json(
      { error: '服务器内部错误' },
      { status: 500 }
    );
  }
}

// PUT /api/contracts/[id] - 更新合同（仅创建者可更新，且合同状态为 rejected 时才能更新）
export async function PUT(request, { params }) {
  try {
    const user = getUserFromRequest(request);
    if (!user) return unauthorizedResponse();

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

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

    // 只有创建者可以更新
    if (contract.creator_id !== user.id) {
      return Response.json(
        { error: '只有合同创建者可以修改' },
        { status: 403 }
      );
    }

    // 只有被驳回的合同才能修改
    if (contract.status !== 'rejected') {
      return Response.json(
        { error: '只有被驳回的合同才能修改' },
        { status: 400 }
      );
    }

    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;

    // 查找合作单位名称
    let partner_name = contract.partner_name;
    if (partner_id && partner_id !== contract.partner_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 }
        );
      }
      partner_name = partner.name;
    }

    // 更新合同并重置状态和审批字段
    db.prepare(`
      UPDATE contracts SET
        project_name = ?,
        partner_id = ?,
        partner_name = ?,
        contract_content = ?,
        contract_years = ?,
        contract_amount = ?,
        estimated_profit = ?,
        payment_type = ?,
        sign_date = ?,
        project_leader = ?,
        status = 'pending_supervisor',
        supervisor_opinion = NULL,
        supervisor_approved = NULL,
        supervisor_id = NULL,
        supervisor_name = NULL,
        supervisor_time = NULL,
        finance_opinion = NULL,
        finance_approved = NULL,
        finance_id = NULL,
        finance_name = NULL,
        finance_time = NULL,
        secretary_opinion = NULL,
        secretary_approved = NULL,
        secretary_id = NULL,
        secretary_name = NULL,
        secretary_time = NULL,
        reject_reason = NULL,
        updated_at = CURRENT_TIMESTAMP
      WHERE id = ?
    `).run(
      project_name || contract.project_name,
      partner_id || contract.partner_id,
      partner_name,
      contract_content !== undefined ? contract_content : contract.contract_content,
      contract_years !== undefined ? contract_years : contract.contract_years,
      contract_amount !== undefined ? contract_amount : contract.contract_amount,
      estimated_profit !== undefined ? estimated_profit : contract.estimated_profit,
      payment_type || contract.payment_type,
      sign_date !== undefined ? sign_date : contract.sign_date,
      project_leader !== undefined ? project_leader : contract.project_leader,
      id
    );

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

    // 获取附件
    const attachments = db.prepare(
      'SELECT * FROM contract_attachments WHERE contract_id = ? ORDER BY created_at DESC'
    ).all(id);

    return Response.json({
      ...updated,
      attachments,
      opinions: buildOpinions(updated),
    });
  } catch (error) {
    console.error('更新合同失败:', error);
    return Response.json(
      { error: '服务器内部错误' },
      { status: 500 }
    );
  }
}
