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

const api = vi.hoisted (() => ({
  isApiError: vi.fn (),
}))

vi.mock ('@/lib/api', () => api)

describe ('extractValidationError', () => {
  it ('extracts field and base errors from 422 validation responses', async () => {
    api.isApiError.mockReturnValueOnce (true)

    const { extractValidationError } = await import ('@/lib/apiErrors')
    const validationError = extractValidationError<'name'> ({
      response: {
        status: 422,
        data:   {
          type:        'validation_error',
          message:     '入力内容を確認してください．',
          errors:      { name: ['名前は必須です．'] },
          base_errors: ['全体エラー'],
        },
      },
    })

    expect (validationError).toEqual ({
      message:     '入力内容を確認してください．',
      fieldErrors: { name: ['名前は必須です．'] },
      baseErrors:  ['全体エラー'],
    })
  })

  it ('preserves dotted field keys for indexed form rows', async () => {
    api.isApiError.mockReturnValueOnce (true)

    const { extractValidationError } = await import ('@/lib/apiErrors')
    const validationError = extractValidationError<'deerjikists.0.platform'> ({
      response: {
        status: 422,
        data:   {
          type:        'validation_error',
          errors:      { 'deerjikists.0.platform': ['プラットフォームを入力してください．'] },
          base_errors: [],
        },
      },
    })

    expect (validationError?.fieldErrors).toEqual ({
      'deerjikists0Platform': ['プラットフォームを入力してください．'],
    })
  })

  it ('does not treat 400 bad requests as form validation errors', async () => {
    api.isApiError.mockReturnValueOnce (true)

    const { extractValidationError } = await import ('@/lib/apiErrors')
    const validationError = extractValidationError ({
      response: {
        status: 400,
        data:   {
          type:        'bad_request',
          message:     'リクエストが不正です．',
          errors:      {},
          base_errors: ['リクエストが不正です．'],
        },
      },
    })

    expect (validationError).toBeNull ()
  })

  it ('ignores non-api errors', async () => {
    api.isApiError.mockReturnValueOnce (false)

    const { extractValidationError } = await import ('@/lib/apiErrors')

    expect (extractValidationError (new Error ('network'))).toBeNull ()
  })
})
