import { describe, expect, it } from 'vitest'

import type { ReservationTaskFieldResult } from '@/types/reservation'
import {
  buildInitialFieldValues,
  buildEditableFieldValues,
  groupReservationFields,
  validateReservationFieldValues,
} from '@/utils/reservationFieldRules'

function createField(overrides: Partial<ReservationTaskFieldResult>): ReservationTaskFieldResult {
  return {
    row_number: 1,
    card_name: 'New Booking',
    display_area: '基础信息',
    field_path: 'guest.name',
    display_name: '客人姓名',
    visible: 'Y',
    editable: 'Y',
    input_editable: 'Y',
    select_editable: 'N',
    date_picker: 'N',
    number_input: 'N',
    file_display: 'N',
    table_editable: 'N',
    enum_options: null,
    required_rule: null,
    display_condition: null,
    validation_rule: null,
    write_path: null,
    opera_write_participation: 'N',
    opera_parameter_mapping: null,
    notes: null,
    value: null,
    ...overrides,
  }
}

describe('validateReservationFieldValues', () => {
  it('validates required, enum, date, and number fields from backend metadata', () => {
    const errors = validateReservationFieldValues(
      [
        createField({
          field_path: 'guest.name',
          display_name: '客人姓名',
          required_rule: 'Y',
        }),
        createField({
          field_path: 'room.type',
          display_name: '房型',
          select_editable: 'Y',
          enum_options: '豪华 Q1A, 行政套房',
        }),
        createField({
          field_path: 'stay.arrival_date',
          display_name: '入住日期',
          date_picker: 'Y',
        }),
        createField({
          field_path: 'room.count',
          display_name: '房间数',
          number_input: 'Y',
        }),
      ],
      {
        'guest.name': '',
        'room.type': '不存在的房型',
        'stay.arrival_date': '2026/07/08',
        'room.count': 'abc',
      },
    )

    expect(errors).toMatchObject({
      'guest.name': {
        code: 'required',
        field_name: '客人姓名',
      },
      'room.type': {
        code: 'enum',
        field_name: '房型',
      },
      'stay.arrival_date': {
        code: 'date',
        field_name: '入住日期',
      },
      'room.count': {
        code: 'number',
        field_name: '房间数',
      },
    })
  })

  it('groups only fields that match the current display condition', () => {
    const groups = groupReservationFields(
      [
        createField({
          field_path: 'case_keys.group_code',
          display_name: 'Group Code',
          display_condition: '对象为Group Block或Allotment时展示',
        }),
        createField({
          field_path: 'case_keys.confirmation_number',
          display_name: 'Confirmation No.',
          display_condition: '对象为FIT Reservation时展示',
        }),
      ],
      '基础信息',
      {
        'extracted_fields.booking_object_type': 'Group Block',
        'case_keys.group_code': 'GRP-001',
      },
    )

    expect(groups.flatMap((group) => group.fields.map((field) => field.field_path))).toEqual(['case_keys.group_code'])
  })

  it('builds a backend-safe editable payload without readonly or inactive fields', () => {
    const payload = buildEditableFieldValues(
      [
        createField({
          field_path: 'visible_reason',
          display_name: '生成原因',
          editable: 'N',
          input_editable: 'N',
          required_rule: 'Y',
        }),
        createField({
          field_path: 'case_keys.group_code',
          display_name: 'Group Code',
          display_condition: '对象为Group Block或Allotment时展示',
        }),
        createField({
          field_path: 'case_keys.confirmation_number',
          display_name: 'Confirmation No.',
          display_condition: '对象为FIT Reservation时展示',
        }),
      ],
      {
        visible_reason: 'AI extracted this task.',
        'case_keys.group_code': 'GRP-001',
        'case_keys.confirmation_number': '',
        'extracted_fields.booking_object_type': 'Group Block',
      },
      false,
    )

    expect(payload).toEqual({
      'case_keys.group_code': 'GRP-001',
    })
  })

  it('hydrates P0 room_items fields from field_values and submits main field_path keys', () => {
    const roomTypeField = createField({
      field_path: 'extracted_fields.room_items.0.room_type_raw',
      field_pointer: '/extracted_fields/room_items/0/room_type_raw',
      legacy_field_path: 'extracted_fields.room_type',
      display_name: '房型原文',
    })
    const pmsCodeField = createField({
      field_path: 'extracted_fields.room_items.0.pms_room_type_code',
      field_pointer: '/extracted_fields/room_items/0/pms_room_type_code',
      legacy_field_path: 'extracted_fields.pms_room_type_code',
      display_name: 'PMS 房型代码',
    })

    const values = buildInitialFieldValues(
      [roomTypeField, pmsCodeField],
      {
        field_values: {
          'extracted_fields.room_items.0.room_type_raw': 'Deluxe Q1A',
          'extracted_fields.room_items.0.pms_room_type_code': 'Q1A',
        },
      },
      '20260711-p0',
    )
    const payload = buildEditableFieldValues([roomTypeField, pmsCodeField], values, false)

    expect(values).toMatchObject({
      'extracted_fields.room_items.0.room_type_raw': 'Deluxe Q1A',
      'extracted_fields.room_items.0.pms_room_type_code': 'Q1A',
    })
    expect(payload).toEqual({
      'extracted_fields.room_items.0.room_type_raw': 'Deluxe Q1A',
      'extracted_fields.room_items.0.pms_room_type_code': 'Q1A',
    })
    expect(payload).not.toHaveProperty('extracted_fields.room_type')
    expect(payload).not.toHaveProperty('extracted_fields.pms_room_type_code')
  })

  it('hydrates P0 fields from nested field_values as a defensive fallback', () => {
    const values = buildInitialFieldValues(
      [
        createField({
          field_path: 'extracted_fields.room_items.0.room_quantity',
          field_pointer: '/extracted_fields/room_items/0/room_quantity',
          legacy_field_path: 'extracted_fields.room_quantity',
          display_name: '房间数量',
        }),
      ],
      {
        field_values: {
          extracted_fields: {
            room_items: [
              {
                room_quantity: 2,
              },
            ],
          },
        },
      },
      '20260711-p0',
    )

    expect(values).toEqual({
      'extracted_fields.room_items.0.room_quantity': 2,
    })
  })

  it('hydrates code-v1 historical fields from legacy_field_values into P0 main keys', () => {
    const values = buildInitialFieldValues(
      [
        createField({
          field_path: 'extracted_fields.room_items.0.pms_room_type_code',
          field_pointer: '/extracted_fields/room_items/0/pms_room_type_code',
          legacy_field_path: 'extracted_fields.pms_room_type_code',
          display_name: 'PMS 房型代码',
        }),
      ],
      {
        field_values: {
          'extracted_fields.room_items.0.pms_room_type_code': 'NEW',
        },
        legacy_field_values: {
          'extracted_fields.pms_room_type_code': 'LEGACY',
        },
      },
      'code-v1',
    )

    expect(values).toEqual({
      'extracted_fields.room_items.0.pms_room_type_code': 'LEGACY',
    })
  })

  it('hydrates code-v1 historical fields from legacy effective_payload when legacy_field_values is absent', () => {
    const values = buildInitialFieldValues(
      [
        createField({
          field_path: 'extracted_fields.room_items.0.pms_room_type_code',
          field_pointer: '/extracted_fields/room_items/0/pms_room_type_code',
          legacy_field_path: 'extracted_fields.pms_room_type_code',
          display_name: 'PMS 房型代码',
        }),
      ],
      {
        effective_payload: {
          extracted_fields: {
            pms_room_type_code: 'LEGACY-NESTED',
          },
        },
      },
      'code-v1',
    )

    expect(values).toEqual({
      'extracted_fields.room_items.0.pms_room_type_code': 'LEGACY-NESTED',
    })
  })

  it('does not create frontend required errors for readonly evidence fields missing in V3 payloads', () => {
    const errors = validateReservationFieldValues(
      [
        createField({
          field_path: 'visible_reason',
          display_name: '生成原因',
          editable: 'N',
          input_editable: 'N',
          required_rule: 'Y',
          value: null,
        }),
        createField({
          field_path: 'extracted_fields.room_items.0.pms_room_type_code',
          display_name: 'PMS 房型代码',
          field_pointer: '/extracted_fields/room_items/0/pms_room_type_code',
          legacy_field_path: 'extracted_fields.pms_room_type_code',
          required_rule: 'Y',
          value: '',
        }),
      ],
      {
        relevant_message_excerpt: 'Please book a Deluxe Q1A room.',
        'extracted_fields.room_items.0.pms_room_type_code': '',
      },
    )

    expect(errors).toEqual({
      'extracted_fields.room_items.0.pms_room_type_code': {
        code: 'required',
        field_name: 'PMS 房型代码',
      },
    })
  })
})
