import { AxiosError } from 'axios';

import {
  isGroupPostNotFoundError,
  isPostNotFoundError,
} from 'src/hooks/useGeneralErrorFilters';
import { ResponseCode } from 'src/types/services';

const createAxiosError = ({
  status = 404,
  code = ResponseCode.GROUP_POST_NOT_FOUND,
  url = '/groups/123/posts/456',
}: {
  status?: number;
  code?: string;
  url?: string;
}) =>
  ({
    config: { url },
    response: {
      status,
      data: { code },
    },
  }) as AxiosError<{ code?: string }>;

describe('isPostNotFoundError', () => {
  const makePostError = ({
    status = 404,
    code = ResponseCode.POST_NOT_FOUND,
    url = '/posts/123',
  }: {
    status?: number;
    code?: string;
    url?: string;
  } = {}) =>
    ({
      config: { url },
      response: { status, data: { code } },
    }) as AxiosError<{ code?: string }>;

  test('returns true for 404 POST_NOT_FOUND on post detail path', () => {
    expect(isPostNotFoundError(makePostError())).toBe(true);
    expect(isPostNotFoundError(makePostError({ url: 'posts/456' }))).toBe(true);
    expect(
      isPostNotFoundError(makePostError({ url: '/posts/123?ref=home' })),
    ).toBe(true);
  });

  test('returns false for group post paths', () => {
    expect(
      isPostNotFoundError(makePostError({ url: '/groups/1/posts/123' })),
    ).toBe(false);
  });

  test('returns false for non-404 status', () => {
    expect(isPostNotFoundError(makePostError({ status: 403 }))).toBe(false);
  });

  test('returns false for different error codes', () => {
    expect(
      isPostNotFoundError(makePostError({ code: ResponseCode.TOKEN_EXPIRED })),
    ).toBe(false);
  });
});

describe('isGroupPostNotFoundError', () => {
  test('returns true for 404 GROUP_POST_NOT_FOUND in group post detail path', () => {
    expect(
      isGroupPostNotFoundError(
        createAxiosError({ url: '/groups/123/posts/456' }),
      ),
    ).toBe(true);
    expect(
      isGroupPostNotFoundError(
        createAxiosError({ url: 'groups/123/posts/456' }),
      ),
    ).toBe(true);
    expect(
      isGroupPostNotFoundError(
        createAxiosError({ url: '/groups/123/posts/456?ref=home' }),
      ),
    ).toBe(true);
  });

  test('returns false for non-group-post paths', () => {
    expect(
      isGroupPostNotFoundError(
        createAxiosError({ url: '/groups/123/comments/456' }),
      ),
    ).toBe(false);
  });

  test('returns false for non-404 statuses', () => {
    expect(
      isGroupPostNotFoundError(
        createAxiosError({
          status: 403,
          url: '/groups/123/posts/456',
        }),
      ),
    ).toBe(false);
  });

  test('returns false for different error codes', () => {
    expect(
      isGroupPostNotFoundError(
        createAxiosError({
          code: ResponseCode.TOKEN_EXPIRED,
          url: '/groups/123/posts/456',
        }),
      ),
    ).toBe(false);
  });
});
