import {
  createItem,
  deleteItem,
  readFiles,
  readFolders,
  readItems,
  updateFile,
  updateItem,
  uploadFiles,
} from "@directus/sdk";
import { buildDirectusAssetUrl } from "@/config/env";

export const listCountdownTimers = async (client, corporateCustomerId) => {
  return await client.request(
    readItems("countdown_timer", {
      filter: {
        corporate_customer: {
          _eq: corporateCustomerId,
        },
      },
    })
  );
};

export const deleteCountdownTimerById = async (client, id) => {
  return await client.request(deleteItem("countdown_timer", id));
};

export const saveCountdownTimerItem = async (client, options) => {
  if (options.mode === "edit") {
    return await client.request(
      updateItem("countdown_timer", options.id, options.item)
    );
  }

  return await client.request(createItem("countdown_timer", options.item));
};

export const listCountdownTimerImages = async (client) => {
  const files = await client.request(
    readFiles({
      filter: {
        type: {
          _contains: "image",
        },
        folder: {
          name: {
            _eq: "Countdown Timer",
          },
        },
      },
      fields: ["id"],
      sort: ["-uploaded_on"],
    })
  );

  return files.map((item) => ({
    url: buildDirectusAssetUrl(item.id),
  }));
};

export const getCountdownTimerFolderId = async (client) => {
  const folders = await client.request(
    readFolders({
      fields: ["id"],
      filter: {
        name: "Countdown Timer",
      },
    })
  );

  return folders[0]?.id || null;
};

export const moveCountdownTimerFileToFolder = async (
  client,
  fileId,
  folderId
) => {
  return await client.request(
    updateFile(fileId, {
      folder: folderId,
    })
  );
};

export const uploadCountdownTimerImage = async (client, file, folderId) => {
  const result = await client.request(uploadFiles(file));
  if (folderId) {
    await moveCountdownTimerFileToFolder(client, result.id, folderId);
  }

  return {
    id: result.id,
    url: buildDirectusAssetUrl(result.id),
  };
};

