import { ExceptionCode } from "../exception-code";
import type { ExceptionResult } from "../exception-result";

export class StorageExceptionHandler {
  static canHandle(error: unknown): error is Error | DOMException {
    if (!isErrorLike(error)) return false;
    const message = error.message.toLowerCase();
    return (
      error.name === "QuotaExceededError" ||
      error.name === "SecurityError" ||
      message.includes("localstorage") ||
      message.includes("indexeddb") ||
      message.includes("quota") ||
      message.includes("storage")
    );
  }

  static handle(error: Error | DOMException): ExceptionResult {
    if (error.name === "QuotaExceededError") {
      return {
        code: ExceptionCode.storage,
        message: "Storage quota exceeded.",
      };
    }

    if (error.name === "SecurityError") {
      return {
        code: ExceptionCode.storage,
        message: "Storage permission denied.",
      };
    }

    return {
      code: ExceptionCode.storage,
      message: "Local data could not be saved. Please try again.",
    };
  }
}

function isErrorLike(error: unknown): error is Error | DOMException {
  if (error instanceof Error) return true;
  return typeof DOMException !== "undefined" && error instanceof DOMException;
}
