import { ConflictException } from '@nestjs/common';
import { Repository } from 'typeorm';
import { JinshujuMatchRule, type JinshujuFieldMapping } from '../entities/jinshuju-match-rule.entity';

export async function getMatchRule(
  repo: Repository<JinshujuMatchRule>,
  id: number,
  formToken: string,
): Promise<JinshujuMatchRule> {
  const rule = await repo.findOne({ where: { id } });
  if (!rule) throw new ConflictException('规则不存在');
  if (rule.formToken !== formToken) {
    throw new ConflictException('匹配规则不属于当前表单');
  }
  return rule;
}

export function validateMatchRule(formToken: string, mappings: JinshujuFieldMapping): void {
  if (!formToken.trim()) throw new ConflictException('表单 Token 不能为空');
  if (!mappings.name) throw new ConflictException('匹配规则必须映射姓名字段');
  const allowedStudentFields = new Set([
    'name',
    'studentNo',
    'phone',
    'idNumber',
    'gender',
    'ethnicity',
    'emergencyContact',
    'emergencyPhone',
  ]);
  for (const [studentField, fieldKey] of Object.entries(mappings)) {
    if (!allowedStudentFields.has(studentField)) {
      throw new ConflictException(`不允许映射学生字段：${studentField}`);
    }
    if (fieldKey && !/^field_\d+$/.test(fieldKey)) {
      throw new ConflictException(`无效的金数据字段：${fieldKey}`);
    }
  }
}

/** Extract value from a Jinshuju entry by field mapping. */
export function extractField(entry: Record<string, unknown>, fieldKey: string | undefined): string {
  if (!fieldKey) return '';
  const val = entry[fieldKey];
  return typeof val === 'string' ? val.trim() : '';
}
