import "dotenv/config";
import "@shopify/shopify-app-remix/adapters/node";
import {
  ApiVersion,
  AppDistribution,
  shopifyApp,
} from "@shopify/shopify-app-remix/server";
import type { Session } from "@shopify/shopify-api";
import type { SessionStorage } from "@shopify/shopify-app-session-storage";
import { restResources } from "@shopify/shopify-api/rest/admin/2025-07";

class MemorySessionStorage implements SessionStorage {
  private sessions: Record<string, Session> = {};

  async storeSession(session: Session) {
    this.sessions[session.id] = session;
    return true;
  }

  async loadSession(id: string) {
    return this.sessions[id];
  }

  async deleteSession(id: string) {
    delete this.sessions[id];
    return true;
  }

  async deleteSessions(ids: string[]) {
    ids.forEach((id) => delete this.sessions[id]);
    return true;
  }

  async findSessionsByShop(shop: string) {
    return Object.values(this.sessions).filter(
      (session) => session.shop === shop,
    );
  }
}

const shopify = shopifyApp({
  apiKey: process.env.SHOPIFY_API_KEY,
  apiSecretKey: process.env.SHOPIFY_API_SECRET || "",
  apiVersion: ApiVersion.January25,
  scopes: [
    "read_customers",
    "write_customers",
    "read_content",
    "write_content",
  ],
  appUrl: process.env.SHOPIFY_APP_URL || "",
  authPathPrefix: "/auth",
  sessionStorage: new MemorySessionStorage(),
  distribution: AppDistribution.AppStore,
  future: {
    unstable_newEmbeddedAuthStrategy: true,
    removeRest: true,
  },
  restResources,
  appProxy: {
    // ストアフロントの /apps/social へのアクセスが
    // アプリの /proxy/social ルートに転送される
    subpath: "social", 
    prefix: "apps",
  },
  webhooks: {
    APP_UNINSTALLED: {
      deliveryMethod: "http",
      callbackUrl: "/webhooks",
    },
  },
  hooks: {
    afterAuth: async ({ session }) => {
      console.log("Authentication successful for shop:", session.shop);
      shopify.registerWebhooks({ session });
    },
  },
  // フロント側のルートを認証システムから除外
  useOnlineTokens: false,
  ...(process.env.SHOP_CUSTOM_DOMAIN
    ? { customShopDomains: [process.env.SHOP_CUSTOM_DOMAIN] }
    : {}),
});

export default shopify;
export const apiVersion = ApiVersion.January25;
export const addDocumentResponseHeaders = shopify.addDocumentResponseHeaders;
export const authenticate = shopify.authenticate;
export const unauthenticated = shopify.unauthenticated;
export const login = shopify.login;
export const registerWebhooks = shopify.registerWebhooks;
export const sessionStorage = shopify.sessionStorage;
