import { apiApp } from '@/api/autoshopee/api';

const BASE = '/shop-manager/shopee-video';

/**
 * @param {string} shopId
 * @returns {Promise<import('@type/ShopeeVideoPost').ShopeeVideoCampaign[]>}
 */
export const apiShopeeVideoCampaignList = async (shopId) => {
  try {
    const result = await apiApp.post(`${BASE}/campaign/list`, { shopId: `${shopId}` });
    return result.data || [];
  } catch (error) {
    return [];
  }
};

/**
 * @param {string} shopId
 * @returns {Promise<{campaigns: number, items: number, done: number, error: number, pending: number}>}
 */
export const apiShopeeVideoCampaignStats = async (shopId) => {
  try {
    const result = await apiApp.post(`${BASE}/campaign/stats`, { shopId: `${shopId}` });
    return result.data || {
      campaigns: 0, items: 0, done: 0, error: 0, pending: 0,
    };
  } catch (error) {
    return {
      campaigns: 0, items: 0, done: 0, error: 0, pending: 0,
    };
  }
};

/**
 * @param {{name: string, shopId: string, shopName: string}} payload
 * @returns {Promise<import('@type/ShopeeVideoPost').ShopeeVideoCampaign|null>}
 */
export const apiShopeeVideoCampaignCreate = async (payload) => {
  try {
    const result = await apiApp.post(`${BASE}/campaign/create`, {
      name: payload.name,
      shopId: `${payload.shopId}`,
      shopName: payload.shopName || '',
    });
    return result.data || null;
  } catch (error) {
    return null;
  }
};

/**
 * @param {string} campaignId
 * @returns {Promise<{campaign: import('@type/ShopeeVideoPost').ShopeeVideoCampaign, items: import('@type/ShopeeVideoPost').ShopeeVideoCampaignItem[]}|null>}
 */
export const apiShopeeVideoCampaignGet = async (campaignId) => {
  try {
    const result = await apiApp.post(`${BASE}/campaign/get`, { campaignId });
    return result.data || null;
  } catch (error) {
    return null;
  }
};

/**
 * @param {string} campaignId
 * @returns {Promise<import('@type/ShopeeVideoPost').ShopeeVideoCampaignItem[]>}
 */
export const apiShopeeVideoItemList = async (campaignId) => {
  try {
    const result = await apiApp.post(`${BASE}/item/list`, { campaignId });
    return result.data || [];
  } catch (error) {
    return [];
  }
};

/**
 * @param {string} campaignId
 * @param {object[]} items
 * @returns {Promise<import('@type/ShopeeVideoPost').ShopeeVideoCampaignItem[]>}
 */
export const apiShopeeVideoItemBulkCreate = async (campaignId, items) => {
  try {
    const result = await apiApp.post(`${BASE}/item/bulk-create`, { campaignId, items });
    return result.data || [];
  } catch (error) {
    return [];
  }
};

/**
 * @param {string} itemId
 * @param {object} patch
 * @returns {Promise<import('@type/ShopeeVideoPost').ShopeeVideoCampaignItem|null>}
 */
export const apiShopeeVideoItemUpdate = async (itemId, patch) => {
  try {
    const result = await apiApp.post(`${BASE}/item/update`, { itemId, patch });
    return result.data || null;
  } catch (error) {
    return null;
  }
};

/**
 * @param {string} campaignId
 * @param {object} patch
 * @returns {Promise<import('@type/ShopeeVideoPost').ShopeeVideoCampaign|null>}
 */
export const apiShopeeVideoCampaignUpdate = async (campaignId, patch) => {
  try {
    const result = await apiApp.post(`${BASE}/campaign/update`, { campaignId, patch });
    return result.data || null;
  } catch (error) {
    return null;
  }
};

/**
 * @param {string} campaignId
 * @returns {Promise<boolean>}
 */
export const apiShopeeVideoCampaignRemove = async (campaignId) => {
  try {
    const result = await apiApp.post(`${BASE}/campaign/remove`, { campaignId });
    return !!(result && result.data && result.data.removed);
  } catch (error) {
    return false;
  }
};

/**
 * @param {string} itemId
 * @returns {Promise<boolean>}
 */
export const apiShopeeVideoItemRemove = async (itemId) => {
  try {
    const result = await apiApp.post(`${BASE}/item/remove`, { itemId });
    return !!(result && result.data && result.data.removed);
  } catch (error) {
    return false;
  }
};

/**
 * @param {{fileName: string, contentType: string}} payload
 * @returns {Promise<import('@type/ShopeeVideoPost').ShopeeVideoLibraryPresign|null>}
 */
export const apiShopeeVideoLibraryPresign = async (payload) => {
  try {
    const result = await apiApp.post(`${BASE}/library/presign`, {
      fileName: payload.fileName,
      contentType: payload.contentType,
    });
    return result.data || null;
  } catch (error) {
    return null;
  }
};

/**
 * @param {Blob} blob
 * @param {string} fileName
 * @returns {Promise<string>}
 */
export const apiShopeeVideoUploadR2 = async (blob, fileName) => {
  const contentType = blob.type || 'video/mp4';

  const presign = await apiShopeeVideoLibraryPresign({ fileName, contentType });

  if (!(presign && presign.uploadUrl && presign.publicUrl)) {
    return '';
  }

  try {
    const response = await fetch(presign.uploadUrl, {
      method: 'PUT',
      body: blob,
      headers: { 'Content-Type': contentType },
    });

    if (!response.ok) {
      return '';
    }

    return presign.publicUrl;
  } catch (error) {
    return '';
  }
};

/**
 * @param {import('@type/ShopeeVideoPost').ShopeeVideoLibraryCommitInput} payload
 * @returns {Promise<import('@type/ShopeeVideoPost').ShopeeVideoLibrary|null>}
 */
export const apiShopeeVideoLibraryCommit = async (payload) => {
  try {
    const result = await apiApp.post(`${BASE}/library/commit`, payload);
    return result.data || null;
  } catch (error) {
    return null;
  }
};

/**
 * @param {{origin?: string, collectionId?: string, limit?: number, skip?: number}} [payload]
 * @returns {Promise<import('@type/ShopeeVideoPost').ShopeeVideoLibrary[]>}
 */
export const apiShopeeVideoLibraryList = async (payload) => {
  try {
    const result = await apiApp.post(`${BASE}/library/list`, payload || {});
    return result.data || [];
  } catch (error) {
    return [];
  }
};

/**
 * @returns {Promise<{count: number, totalSize: number}>}
 */
export const apiShopeeVideoLibraryStats = async () => {
  try {
    const result = await apiApp.post(`${BASE}/library/stats`, {});
    return result.data || { count: 0, totalSize: 0 };
  } catch (error) {
    return { count: 0, totalSize: 0 };
  }
};

/**
 * @param {string} libraryId
 * @returns {Promise<boolean>}
 */
export const apiShopeeVideoLibraryRemove = async (libraryId) => {
  try {
    const result = await apiApp.post(`${BASE}/library/remove`, { libraryId });
    return !!(result && result.data && result.data.removed);
  } catch (error) {
    return false;
  }
};

/**
 * @param {string} libraryId
 * @param {string|null} collectionId
 * @returns {Promise<import('@type/ShopeeVideoPost').ShopeeVideoLibrary|null>}
 */
export const apiShopeeVideoLibraryMove = async (libraryId, collectionId) => {
  try {
    const result = await apiApp.post(`${BASE}/library/move`, { libraryId, collectionId });
    return result.data || null;
  } catch (error) {
    return null;
  }
};

/**
 * @returns {Promise<{collections: import('@type/ShopeeVideoPost').ShopeeVideoCollection[], uncategorized: number, total: number}>}
 */
export const apiShopeeVideoCollectionList = async () => {
  try {
    const result = await apiApp.post(`${BASE}/collection/list`, {});
    return result.data || { collections: [], uncategorized: 0, total: 0 };
  } catch (error) {
    return { collections: [], uncategorized: 0, total: 0 };
  }
};

/**
 * @param {{name: string, parentId?: string}} payload
 * @returns {Promise<import('@type/ShopeeVideoPost').ShopeeVideoCollection|null>}
 */
export const apiShopeeVideoCollectionCreate = async (payload) => {
  try {
    const result = await apiApp.post(`${BASE}/collection/create`, {
      name: payload.name,
      parentId: payload.parentId || null,
    });
    return result.data || null;
  } catch (error) {
    return null;
  }
};

/**
 * @param {string} collectionId
 * @param {object} patch
 * @returns {Promise<import('@type/ShopeeVideoPost').ShopeeVideoCollection|null>}
 */
export const apiShopeeVideoCollectionUpdate = async (collectionId, patch) => {
  try {
    const result = await apiApp.post(`${BASE}/collection/update`, { collectionId, patch });
    return result.data || null;
  } catch (error) {
    return null;
  }
};

/**
 * @param {string} collectionId
 * @returns {Promise<boolean>}
 */
export const apiShopeeVideoCollectionRemove = async (collectionId) => {
  try {
    const result = await apiApp.post(`${BASE}/collection/remove`, { collectionId });
    return !!(result && result.data && result.data.removed);
  } catch (error) {
    return false;
  }
};
