import { updateInstanceConfig } from "@/instance-config";
import {
  type InstanceProfile,
  type InstanceSetting,
  type InstanceSetting_GeneralSetting,
  type InstanceSetting_MemoRelatedSetting,
  type InstanceSetting_StorageSetting,
  InstanceSetting_StorageSetting_StorageType,
} from "@/types/proto/api/v1/instance_service_pb";
import { fetchJson, parseResourceId, API_ORIGIN } from "./apiClient";
import type { ApiInstanceInfo } from "./types";

const defaultInstanceGeneralSetting: InstanceSetting_GeneralSetting = {
  disallowUserRegistration: false,
  disallowPasswordAuth: false,
  additionalScript: "",
  additionalStyle: "",
  customProfile: {
    title: "",
    description: "",
    logoUrl: "",
  },
  weekStartDayOffset: 0,
  disallowChangeUsername: false,
  disallowChangeNickname: false,
};

const defaultInstanceMemoSetting: InstanceSetting_MemoRelatedSetting = {
  disallowPublicVisibility: false,
  displayWithUpdateTime: false,
  contentLengthLimit: 0,
  enableDoubleClickEdit: true,
  reactions: [],
};

const defaultInstanceStorageSetting: InstanceSetting_StorageSetting = {
  storageType: InstanceSetting_StorageSetting_StorageType.LOCAL,
  filepathTemplate: "",
  uploadSizeLimitMb: BigInt(50),
};

const buildInstanceSetting = (name: string): InstanceSetting => {
  const key = parseResourceId(name);
  if (key === "GENERAL") {
    return { name, value: { case: "generalSetting", value: defaultInstanceGeneralSetting } };
  }
  if (key === "MEMO_RELATED") {
    return { name, value: { case: "memoRelatedSetting", value: defaultInstanceMemoSetting } };
  }
  if (key === "STORAGE") {
    return { name, value: { case: "storageSetting", value: defaultInstanceStorageSetting } };
  }
  return { name, value: { case: "generalSetting", value: defaultInstanceGeneralSetting } };
};

export const instanceServiceClient = {
  async getInstanceProfile(_request?: unknown): Promise<InstanceProfile> {
    void _request;
    const data = await fetchJson<ApiInstanceInfo>("/instance", { method: "GET" });
    const instanceUrl = API_ORIGIN;
    return {
      owner: "users/1",
      version: typeof data?.version === "string" ? data.version : "",
      mode: typeof data?.mode === "string" ? data.mode : "dev",
      instanceUrl,
    };
  },
  async getInstanceSetting(request: { name: string }): Promise<InstanceSetting> {
    return buildInstanceSetting(request.name);
  },
  async updateInstanceSetting(request: { setting?: InstanceSetting }): Promise<InstanceSetting> {
    if (request.setting) {
      return request.setting;
    }
    return buildInstanceSetting("instance/settings/GENERAL");
  },
};

