import httpClient from "../../utils/http-client";

interface ToggleStatusConfig {
  toggleUrl: string;
}

interface ToggleStatusData {
  isLoading: boolean;
  error: string | null;
  togglePosition(id: number): Promise<void>;
}

export function toggleStatus(config: ToggleStatusConfig): ToggleStatusData {
  return {
    isLoading: false,
    error: null,

    async togglePosition(): Promise<void> {
      this.isLoading = true;
      this.error = null;

      const csrfToken =
        document
          .querySelector('meta[name="csrf-token"]')
          ?.getAttribute("content") || "";

      try {
        const response = await httpClient.post(
          config.toggleUrl,
          {},
          {
            headers: {
              "X-CSRF-TOKEN": csrfToken,
              "Content-Type": "application/json",
              Accept: "application/json",
            },
          }
        );

        if (response.data.success) {
          // Reload the page to reflect the new order
          window.location.reload();
        } else {
          this.error = "ステータス変更に失敗しました";
          console.error("Status change failed:", this.error);
          alert(this.error);
        }
      } catch (error) {
        this.error = "通信エラーが発生しました";
        console.error("Status change error:", error);
        alert(this.error);
      } finally {
        this.isLoading = false;
      }
    },
  };
}

// Alpine.js データオブジェクトとして登録
document.addEventListener("alpine:init", () => {
  Alpine.data("toggleStatus", toggleStatus);
});
