# API Error Handling — Implementation Plan

> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development or superpowers:executing-plans.

**Goal:** Создать `useMutationWithToast` обёртку, улучшить `getApiErrorMessage`, исправить CheckoutPage error display.

**Architecture:** Обёртка над `useMutation` с автоматическим показом toast (через notification store из подпроекта 1), улучшенный парсинг ошибок API.

**Tech Stack:** TypeScript, TanStack React Query, Vitest

**Depends on:** Subproject 1 (toast notifications store)

---

### Task 1: Улучшить getApiErrorMessage

**Files:**
- Modify: `client/src/shared/lib/get-api-error-message.ts`
- Test: modify existing or add new tests

- [ ] **Step 1: Write/update tests**

```ts
// client/src/shared/lib/__tests__/get-api-error-message.test.ts
import { describe, it, expect } from 'vitest'
import { getApiErrorMessage } from '../get-api-error-message'

describe('getApiErrorMessage', () => {
  it('returns server error message when axios error has response.data.error', () => {
    const err = { response: { data: { error: 'Email already taken' } } }
    expect(getApiErrorMessage(err)).toBe('Email already taken')
  })

  it('returns network error message when no response', () => {
    const err = { message: 'Network Error', code: 'ERR_NETWORK' }
    expect(getApiErrorMessage(err)).toBe('Нет соединения с сервером. Проверьте подключение к интернету.')
  })

  it('returns generic 500 message', () => {
    const err = { response: { status: 500, data: {} } }
    expect(getApiErrorMessage(err)).toBe('Произошла ошибка. Попробуйте повторить позже.')
  })

  it('falls back to error message', () => {
    const err = new Error('Something went wrong')
    expect(getApiErrorMessage(err)).toBe('Something went wrong')
  })

  it('handles unknown error shape', () => {
    expect(getApiErrorMessage({})).toBe('Произошла неизвестная ошибка')
  })
})
```

- [ ] **Step 2: Run to see failure**

Run: `cd client && npx vitest run shared/lib/__tests__/get-api-error-message.test.ts`
Expected: FAIL (existing tests may not cover new cases)

- [ ] **Step 3: Implement improved getApiErrorMessage**

```ts
// client/src/shared/lib/get-api-error-message.ts
import { isAxiosError } from 'axios'

export function getApiErrorMessage(error: unknown): string {
  if (!error) return 'Произошла неизвестная ошибка'

  if (isAxiosError(error)) {
    if (error.response?.data?.error && typeof error.response.data.error === 'string') {
      return error.response.data.error
    }
    if (!error.response) {
      return 'Нет соединения с сервером. Проверьте подключение к интернету.'
    }
    if (error.response.status >= 500) {
      return 'Произошла ошибка. Попробуйте повторить позже.'
    }
  }

  if (error instanceof Error) {
    return error.message
  }

  return 'Произошла неизвестная ошибка'
}
```

- [ ] **Step 4: Run tests**

Run: `cd client && npx vitest run shared/lib/__tests__/get-api-error-message.test.ts`
Expected: PASS

- [ ] **Step 5: Commit**

```bash
git add client/src/shared/lib/get-api-error-message.ts client/src/shared/lib/__tests__/get-api-error-message.test.ts
git commit -m "feat: improve getApiErrorMessage with user-friendly messages"
```

---

### Task 2: useMutationWithToast обёртка

**Files:**
- Create: `client/src/shared/lib/use-mutation-with-toast.ts`
- Test: `client/src/shared/lib/__tests__/use-mutation-with-toast.test.tsx`

- [ ] **Step 1: Write failing tests**

```tsx
// client/src/shared/lib/__tests__/use-mutation-with-toast.test.tsx
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { renderHook, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { useMutationWithToast } from '../use-mutation-with-toast'
import { addNotification } from '../../model/notification'

vi.mock('../../model/notification', () => ({
  addNotification: vi.fn(),
}))

function createWrapper() {
  const qc = new QueryClient()
  return ({ children }: { children: React.ReactNode }) => (
    <QueryClientProvider client={qc}>{children}</QueryClientProvider>
  )
}

describe('useMutationWithToast', () => {
  beforeEach(() => {
    vi.clearAllMocks()
  })

  it('shows success toast on success', async () => {
    const mutationFn = vi.fn().mockResolvedValue({ ok: true })

    const { result } = renderHook(
      () => useMutationWithToast({ mutationFn, successMessage: 'Done!' }),
      { wrapper: createWrapper() },
    )

    result.current.mutate()
    await waitFor(() => expect(result.current.isSuccess).toBe(true))

    expect(addNotification).toHaveBeenCalledWith({ type: 'success', message: 'Done!' })
  })

  it('shows error toast on error', async () => {
    const mutationFn = vi.fn().mockRejectedValue(new Error('Boom'))

    const { result } = renderHook(
      () => useMutationWithToast({ mutationFn }),
      { wrapper: createWrapper() },
    )

    result.current.mutate()
    await waitFor(() => expect(result.current.isError).toBe(true))

    expect(addNotification).toHaveBeenCalledWith({ type: 'error', message: 'Boom' })
  })

  it('calls user-provided onSuccess', async () => {
    const mutationFn = vi.fn().mockResolvedValue({ ok: true })
    const onSuccess = vi.fn()

    const { result } = renderHook(
      () => useMutationWithToast({ mutationFn, onSuccess, successMessage: 'Done!' }),
      { wrapper: createWrapper() },
    )

    result.current.mutate()
    await waitFor(() => expect(result.current.isSuccess).toBe(true))

    expect(onSuccess).toHaveBeenCalled()
  })

  it('does not show success toast if no successMessage', async () => {
    const mutationFn = vi.fn().mockResolvedValue({ ok: true })

    const { result } = renderHook(
      () => useMutationWithToast({ mutationFn }),
      { wrapper: createWrapper() },
    )

    result.current.mutate()
    await waitFor(() => expect(result.current.isSuccess).toBe(true))

    expect(addNotification).not.toHaveBeenCalled()
  })
})
```

- [ ] **Step 2: Run to verify failure**

Run: `cd client && npx vitest run shared/lib/__tests__/use-mutation-with-toast.test.tsx`
Expected: FAIL

- [ ] **Step 3: Implement useMutationWithToast**

```ts
// client/src/shared/lib/use-mutation-with-toast.ts
import { useMutation, type UseMutationOptions } from '@tanstack/react-query'
import { addNotification } from '../model/notification'
import { getApiErrorMessage } from './get-api-error-message'

type MutationWithToastOptions<TData, TError, TVariables, TContext> =
  UseMutationOptions<TData, TError, TVariables, TContext> & {
    successMessage?: string
  }

export function useMutationWithToast<TData = unknown, TError = unknown, TVariables = void, TContext = unknown>(
  options: MutationWithToastOptions<TData, TError, TVariables, TContext>,
) {
  const { successMessage, onSuccess, onError, ...mutationOptions } = options

  return useMutation({
    ...mutationOptions,
    onSuccess: (data, variables, context) => {
      if (successMessage) {
        addNotification({ type: 'success', message: successMessage })
      }
      onSuccess?.(data, variables, context)
    },
    onError: (error, variables, context) => {
      addNotification({ type: 'error', message: getApiErrorMessage(error) })
      onError?.(error, variables, context)
    },
  })
}
```

- [ ] **Step 4: Run tests**

Run: `cd client && npx vitest run shared/lib/__tests__/use-mutation-with-toast.test.tsx`
Expected: PASS

- [ ] **Step 5: Commit**

```bash
git add client/src/shared/lib/use-mutation-with-toast.ts client/src/shared/lib/__tests__/use-mutation-with-toast.test.tsx
git commit -m "feat: add useMutationWithToast wrapper"
```

---

### Task 3: Исправить CheckoutPage error display

**Files:**
- Modify: `client/src/pages/checkout/CheckoutPage.tsx`

- [ ] **Step 1: Найти прямой вызов error.message**

Search for: `(createMut.error as Error).message`

- [ ] **Step 2: Заменить на getApiErrorMessage**

Before:
```tsx
{createMut.isError && (
  <Alert severity="error">
    {(createMut.error as Error).message}
  </Alert>
)}
```

After:
```tsx
import { getApiErrorMessage } from '@/shared/lib/get-api-error-message'

{createMut.isError && (
  <Alert severity="error">
    {getApiErrorMessage(createMut.error)}
  </Alert>
)}
```

- [ ] **Step 3: Run lint + test + build**

```bash
cd client && npm run lint && npm test && npm run build
```

- [ ] **Step 4: Commit**

```bash
git add client/src/pages/checkout/CheckoutPage.tsx
git commit -m "fix: use getApiErrorMessage in CheckoutPage for user-friendly error display"
```
