/**
 * 电子签署服务
 * 提供自动创建签署记录的公共方法，供其他业务模块调用
 */
import prisma from '../lib/prisma'
import { createEvidence } from './evidence.service'
import { renderTemplate, getTemplateById } from './template.service'

/** 场景与模板ID的映射 */
const SCENE_TEMPLATE_MAP: Record<string, string | null> = {
  CONTRACT: 'tpl_fixed_term_contract',
  RESIGNATION: 'tpl_termination_agreement',
  POLICY: null,
  PAYSLIP: null,
  ONBOARDING: null,
}

/**
 * 自动创建电子签署记录
 * @param params.orgId 组织ID
 * @param params.employeeId 员工ID
 * @param params.scene 签署场景
 * @param params.documentTitle 文件标题
 * @param params.contractId 关联合同ID（可选）
 * @param params.remark 备注（可选）
 * @param params.createdBy 创建人用户ID
 * @param params.templateVars 模板变量（可选）
 * @returns 创建的 ESignRecord 或 null（创建失败时）
 */
export async function autoCreateEsignRecord(params: {
  orgId: string
  employeeId: string
  scene: string
  documentTitle: string
  contractId?: string
  remark?: string
  createdBy: string
  templateVars?: Record<string, string>
}): Promise<any | null> {
  try {
    const { orgId, employeeId, scene, documentTitle, contractId, remark, createdBy, templateVars } = params

    // 获取员工信息
    const employee = await prisma.employee.findFirst({
      where: { id: employeeId, orgId },
      select: { id: true, name: true, phone: true, idCardNumber: true, position: true, monthlySalary: true, department: true },
    })
    if (!employee) return null

    // 自动渲染文件内容
    let documentContent = ''
    const templateId = SCENE_TEMPLATE_MAP[scene]
    if (templateId) {
      const template = getTemplateById(templateId)
      if (template) {
        const org = await prisma.organization.findUnique({ where: { id: orgId }, select: { name: true } })
        const vars: Record<string, string> = {
          companyName: org?.name || '',
          employeeName: employee.name || '',
          idCard: employee.idCardNumber || '',
          position: employee.position || '',
          monthlySalary: String(employee.monthlySalary || ''),
          department: employee.department || '',
          ...templateVars,
        }
        documentContent = renderTemplate(templateId, vars) || ''
      }
    }

    // 创建签署记录
    const record = await prisma.eSignRecord.create({
      data: {
        orgId,
        contractId: contractId || null,
        employeeId,
        scene,
        signMethod: 'ELECTRONIC',
        documentTitle,
        documentContent: documentContent || null,
        status: 'PENDING',
        initiatedBy: createdBy,
        createdBy,
        remark: remark || null,
        expiredAt: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
      },
    })

    // 创建证据链
    await createEvidence({
      orgId,
      category: 'CONTRACT_SIGN',
      refId: record.id,
      employeeId,
      events: [{
        action: `自动发起电子签署：${documentTitle}`,
        timestamp: new Date().toISOString(),
        location: `场景：${scene}，触发：系统自动`,
      }],
      createdBy,
    }).catch(() => {})

    return record
  } catch (err) {
    // 自动创建失败不阻断主流程
    return null
  }
}
