import { BadRequestException } from '@nestjs/common';
import { AiChartService } from './ai-chart.service';

const service = new AiChartService();

const validSchema = {
  title: '各班级人数',
  chartType: 'bar',
  columns: [
    { key: 'className', title: '班级' },
    { key: 'count', title: '人数' },
  ],
  rows: [
    { className: '一班', count: 20 },
    { className: '二班', count: 15 },
  ],
};

describe('AiChartService', () => {
  it('校验通过的图表保留 id、列与行', () => {
    const chart = service.createChart(validSchema);
    expect(chart.id).toBeTruthy();
    expect(chart.chartType).toBe('bar');
    expect(chart.columns).toEqual(validSchema.columns);
    expect(chart.rows).toEqual(validSchema.rows);
  });

  it.each(['line', 'bar', 'pie', 'area', 'radar', 'gauge', 'funnel'])(
    '支持 %s 图表类型',
    (chartType) => {
      const chart = service.createChart({ ...validSchema, chartType });
      expect(chart.chartType).toBe(chartType);
    },
  );

  it('支持散点图并要求至少 3 列', () => {
    const chart = service.createChart({
      ...validSchema,
      chartType: 'scatter',
      columns: [
        { key: 'className', title: '班级' },
        { key: 'capacity', title: '容量' },
        { key: 'occupied', title: '入住人数' },
      ],
    });
    expect(chart.chartType).toBe('scatter');
    expect(() =>
      service.createChart({ ...validSchema, chartType: 'scatter' }),
    ).toThrow('散点图需要 3 列');
  });

  it.each([
    ['标题缺失', { chartType: 'bar', columns: validSchema.columns, rows: [] }, '标题'],
    ['类型不支持', { ...validSchema, chartType: 'hack' }, '图表类型不支持'],
    ['列不足', { ...validSchema, columns: [{ key: 'x', title: 'X' }] }, '至少需要 2 列'],
    ['列过多', {
      ...validSchema,
      columns: Array.from({ length: 11 }, (_, i) => ({ key: `c${i}`, title: `列${i}` })),
    }, '不能超过 10'],
    ['列名非法', { ...validSchema, columns: [{ key: '类 别', title: 'X' }, { key: 'n', title: 'N' }] }, '只能包含'],
    ['列名重复', {
      ...validSchema,
      columns: [{ key: 'x', title: 'A' }, { key: 'x', title: 'B' }],
    }, '列名重复'],
    ['行数超限', {
      ...validSchema,
      rows: Array.from({ length: 501 }, (_, i) => ({ className: `班${i}`, count: 1 })),
    }, '不能超过 500'],
    ['单元格类型非法', {
      ...validSchema,
      rows: [{ className: '一班', count: { hack: true } }],
    }, '类型不支持'],
    ['未知顶层字段', { ...validSchema, extra: 1 }, '未知属性'],
  ])('非法图表被拒绝：%s', async (_name, schema, messagePart) => {
    expect(() => service.createChart(schema)).toThrow(BadRequestException);
    expect(() => service.createChart(schema)).toThrow(messagePart);
  });

  it('行内未知列被剔除', () => {
    const chart = service.createChart({
      ...validSchema,
      rows: [{ className: '一班', count: 20, token: 'secret' }],
    });
    expect(chart.rows[0]).toEqual({ className: '一班', count: 20 });
  });
});
