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

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

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

export const listCardsByFilter = async (client, filter) => {
  return await client.request(
    readItems("marketing_card", {
      filter,
    })
  );
};

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

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

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

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

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

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

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

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

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

