import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn } from 'typeorm';

/**
 * Field mappings from Jinshuju field keys (field_1, field_2, ...) to Student columns.
 * Only mapped fields are extracted; unmapped fields are ignored.
 */
export interface JinshujuFieldMapping {
  /** Jinshuju field key → Student column name */
  name?: string;         // e.g. "field_1"
  phone?: string;        // e.g. "field_2"
  idNumber?: string;     // e.g. "field_3"
  gender?: string;
  ethnicity?: string;
  emergencyContact?: string;
  emergencyPhone?: string;
  studentNo?: string;
}

const mappingTransformer = {
  to(value: JinshujuFieldMapping): string {
    return JSON.stringify(value);
  },
  from(value: string | null): JinshujuFieldMapping {
    if (!value) return {};
    return JSON.parse(value);
  },
};

@Entity('jinshuju_match_rules')
export class JinshujuMatchRule {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ length: 100 })
  name: string;

  @Column({ name: 'form_token', length: 64 })
  formToken: string;

  @Column({ type: 'text', transformer: mappingTransformer })
  mappings: JinshujuFieldMapping;

  @CreateDateColumn({ name: 'created_at' })
  createdAt: Date;

  @UpdateDateColumn({ name: 'updated_at' })
  updatedAt: Date;
}
