import { BadRequestException } from '@nestjs/common';
import {
  expandStageSheets,
  resolveAssignedSheets,
  resolveSheetMapping,
  suggestMapping,
} from './imports.mapping';
import type { ImportStageRequest } from './imports.types';

describe('expandStageSheets', () => {
  it('sheets 优先并去重、去空', () => {
    const stage: ImportStageRequest = {
      stepKey: 'checkins',
      sheet: '旧表',
      sheets: ['四人间女', '四人间男', '', '四人间女'],
    };
    expect(expandStageSheets(stage)).toEqual(['四人间女', '四人间男']);
  });

  it('无 sheets 时回退 sheet', () => {
    expect(expandStageSheets({ stepKey: 'students', sheet: '学生' })).toEqual(['学生']);
  });

  it('两者都缺时返回空数组', () => {
    expect(expandStageSheets({ stepKey: 'students' })).toEqual([]);
  });
});

describe('resolveAssignedSheets', () => {
  const available = ['学生', '四人间女', '四人间男', '2号楼'];

  it('按 sheets 数组收集一个阶段的多张工作表', () => {
    const stages: ImportStageRequest[] = [
      { stepKey: 'checkins', sheets: ['四人间女', '四人间男'] },
      { stepKey: 'checkins', sheets: ['2号楼'] },
    ];
    expect(resolveAssignedSheets(stages, 'checkins', available)).toEqual([
      '四人间女',
      '四人间男',
      '2号楼',
    ]);
  });

  it('兼容旧 sheet 单表形态', () => {
    expect(resolveAssignedSheets([{ stepKey: 'students', sheet: '学生' }], 'students', available)).toEqual([
      '学生',
    ]);
  });

  it('引用不存在的工作表时报错', () => {
    expect(() =>
      resolveAssignedSheets([{ stepKey: 'checkins', sheets: ['不存在'] }], 'checkins', available),
    ).toThrow(BadRequestException);
  });
});

describe('resolveSheetMapping', () => {
  it('确认映射表头存在时优先使用，否则回退该表建议', () => {
    const confirmed = { name: '姓名', roomNumber: '宿舍号' };
    const mapping = resolveSheetMapping(confirmed, ['学生姓名', '房号', '入住日期'], 'checkins');
    expect(mapping).toEqual({
      name: '学生姓名',
      roomNumber: '房号',
      checkInDate: '入住日期',
    });
  });

  it('确认映射为空时退化为该表的 suggestMapping', () => {
    const mapping = resolveSheetMapping(null, ['姓名', '学号', '宿舍号', '入住日期'], 'checkins');
    expect(mapping).toEqual(suggestMapping(['姓名', '学号', '宿舍号', '入住日期'], 'checkins'));
  });
});
