import { Prisma } from '@/generated/prisma/client';

export type ErrorBody = {
  message?: unknown;
  code?: unknown;
  status?: unknown;
};

function hasErrorBody(error: unknown): error is { body: ErrorBody } {
  return (
    typeof error === 'object' &&
    error !== null &&
    'body' in error &&
    typeof (error as any).body === 'object'
  );
}

export function parseError(error: unknown): {
  message: string;
  code?: string;
  status?: number;
} {
  // Recognize AppError even if it's a plain object from network
  if (
    typeof error === 'object' &&
    error !== null &&
    'name' in error &&
    (error as any).name === 'AppError' &&
    'code' in error &&
    'message' in error &&
    'status' in error
  ) {
    return {
      message: (error as any).message,
      code: (error as any).code,
      status: (error as any).status,
    };
  }

  // better-auth / fetch error (có body)
  if (hasErrorBody(error)) {
    return {
      message:
        typeof error.body.message === 'string'
          ? error.body.message
          : 'Unknown error',
      code: typeof error.body.code === 'string' ? error.body.code : undefined,
      status:
        typeof error.body.status === 'number' ? error.body.status : undefined,
    };
  }

  // Prisma (giữ nguyên code như "P2002")
  if (error instanceof Prisma.PrismaClientKnownRequestError) {
    return {
      message: error.message,
      code: error.code,
      status: 400,
    };
  }

  // Error thường
  if (error instanceof Error) {
    return {
      message: error.message,
      code: 'NORMAL_ERROR',
      status: undefined,
    };
  }

  // Fallback
  return {
    message: String(error),
    code: 'NORMAL_ERROR',
    status: undefined,
  };
}
