import lodash from 'lodash';
import { loggerShopee } from '@/plugins/logger';
import { apiShopeeSeller } from '@/api/shopee/seller/init';
import { apiVideoCreator } from './init';

/**
 * @param {object} config
 * @param {import('@type/Shopee/Video/Creator').ShopeeVideoRequestOptions} [opts]
 * @returns {Promise<any>}
 */
export const creatorRequest = async (config, opts = {}) => {
  const {
    errorMsg, dataPath, defaultValue, errorContext = {}, client = apiVideoCreator,
  } = opts;

  try {
    const result = await client.request(config);

    if (dataPath !== undefined) {
      return lodash.get(result, dataPath, defaultValue);
    }

    return result;
  } catch (error) {
    if (errorMsg) {
      loggerShopee.error({
        msg: errorMsg,
        error,
        ...errorContext,
      });
    }

    return defaultValue;
  }
};

/**
 * @returns {Promise<import('@type/Shopee/Video/Creator').ShopeeVideoVerifyInfo|null>}
 */
export const getVideoVerifyInfo = async () => {
  return creatorRequest(
    { method: 'GET', url: '/publish/pc/api/getVerifyInfo' },
    { dataPath: 'data', errorMsg: 'GET_VIDEO_VERIFY_INFO_ERROR', defaultValue: null },
  );
};

/**
 * @returns {Promise<object|null>}
 */
export const getVideoNotice = async () => {
  return creatorRequest(
    { method: 'GET', url: '/publish/pc/api/notice/get' },
    { dataPath: 'data', errorMsg: 'GET_VIDEO_NOTICE_ERROR', defaultValue: null },
  );
};

/**
 * @param {number} page
 * @param {number} pageSize
 * @param {string} order
 * @param {string} orderBy
 * @returns {Promise<import('@type/Shopee/Video/Creator').ShopeeVideoListResult>}
 */
export const getVideoList = async (page = 1, pageSize = 10, order = 'ptime', orderBy = 'desc') => {
  return creatorRequest(
    {
      method: 'GET',
      url: '/publish/pc/api/video/list',
      params: {
        page, pageSize, order, orderBy,
      },
    },
    {
      dataPath: 'data',
      errorMsg: 'GET_VIDEO_LIST_ERROR',
      defaultValue: {
        total: 0, totalPage: 0, page, pageSize, list: [],
      },
    },
  );
};

/**
 * @param {string} vid
 * @param {string} caption
 * @param {number} [maxAttempt]
 * @returns {Promise<string>}
 */
export const findPublishedVideoId = async (vid, caption, maxAttempt = 3) => {
  const targetVid = `${vid || ''}`;
  const targetCaption = `${caption || ''}`.trim();

  for (let attempt = 0; attempt < maxAttempt; attempt += 1) {
    const result = await getVideoList(1, 10, 'ptime', 'desc');
    const list = (result && result.list) || [];

    if (targetVid) {
      const byVid = list.find((item) => `${item.mmsVid}` === targetVid);

      if (byVid && byVid.videoId) {
        return `${byVid.videoId}`;
      }
    }

    const first = list[0];

    if (first && `${first.caption || ''}`.trim() === targetCaption && first.videoId) {
      return `${first.videoId}`;
    }

    if (attempt < maxAttempt - 1) {
      await new Promise((resolve) => {
        setTimeout(resolve, 2000);
      });
    }
  }

  return '';
};

/**
 * Map detail Shopee (postInfo + trend) sang patch cập nhật item backend.
 * @param {import('@type/Shopee/Video/Creator').ShopeeVideoDetail} detail
 * @param {string} [syncedAt]
 * @returns {import('@type/Shopee/Video/Creator').ShopeeVideoInfoPatch}
 */
export const buildVideoInfoPatch = (detail, syncedAt) => {
  if (!detail) {
    return {};
  }

  const postInfo = detail.postInfo || {};
  const trend = detail.trend || {};

  return {
    postId: postInfo.postId ? `${postInfo.postId}` : '',
    encodePostId: postInfo.encodePostId || '',
    postTitle: postInfo.title || '',
    postType: postInfo.postType || 0,
    ptime: postInfo.ptime || 0,
    cover: postInfo.cover || '',
    videoUrl: postInfo.url || '',
    productsCnt: postInfo.productsCnt || 0,
    duration: postInfo.duration || 0,
    viewCount: trend.views || 0,
    likeCount: trend.likes || 0,
    commentCount: trend.comments || 0,
    shareCount: trend.shares || 0,
    followerCount: trend.followers || 0,
    soldCount: trend.soldItems || 0,
    placedOrders: trend.placedOrders || 0,
    placedSales: trend.placedSales || 0,
    productClicks: trend.productClicks || 0,
    productClickRate: trend.productClickRate || 0,
    uniqueBuyers: trend.uniqueBuyers || 0,
    conversionRate: trend.conversionRate || 0,
    salesPerOrder: trend.salesPerOrder || 0,
    salesPerBuyer: trend.salesPerBuyer || 0,
    metricsSyncedAt: syncedAt || new Date().toISOString(),
  };
};

/**
 * @param {string} mmsVid
 * @returns {Promise<import('@type/Shopee/Video/Creator').ShopeeVideoVidInfo|null>}
 */
export const getVideoVidInfo = async (mmsVid) => {
  return creatorRequest(
    { method: 'GET', url: '/publish/pc/api/vid/info', params: { mmsVid } },
    { dataPath: 'data.format', errorMsg: 'GET_VIDEO_VID_INFO_ERROR', defaultValue: null },
  );
};

/**
 * @param {string} hashtagName
 * @param {number} limit
 * @returns {Promise<import('@type/Shopee/Video/Creator').ShopeeVideoHashtag[]>}
 */
export const searchVideoHashtag = async (hashtagName, limit = 20) => {
  return creatorRequest(
    { method: 'POST', url: '/publish/pc/api/hashtag/search', data: { hashtagName, limit } },
    { dataPath: 'data', errorMsg: 'SEARCH_VIDEO_HASHTAG_ERROR', defaultValue: [] },
  );
};

/**
 * @param {number} page
 * @param {number} pageSize
 * @param {string} itemName
 * @returns {Promise<import('@type/Shopee/Video/Creator').ShopeeVideoItemListResult>}
 */
export const getVideoItemList = async (page = 1, pageSize = 10, itemName = '') => {
  return creatorRequest(
    {
      method: 'GET',
      url: '/publish/pc/api/item/list',
      params: { page, pageSize, itemName },
    },
    {
      dataPath: 'data',
      errorMsg: 'GET_VIDEO_ITEM_LIST_ERROR',
      defaultValue: {
        total: 0, totalPage: 0, page, pageSize, items: [],
      },
    },
  );
};

/**
 * @param {boolean} musicCopyright
 * @returns {Promise<any>}
 */
export const upsertVideoPublishUserInfo = async (musicCopyright = true) => {
  return creatorRequest(
    { method: 'POST', url: '/publish/pc/api/upsertPublishUserInfo', data: { musicCopyright } },
    { errorMsg: 'UPSERT_VIDEO_PUBLISH_USER_INFO_ERROR', defaultValue: null },
  );
};

/**
 * @returns {Promise<string>}
 */
export const createVideoTask = async () => {
  return creatorRequest(
    { method: 'POST', url: '/publish/pc/api/task/create', data: {} },
    { dataPath: 'data.taskId', errorMsg: 'CREATE_VIDEO_TASK_ERROR', defaultValue: '' },
  );
};

/**
 * @param {import('@type/Shopee/Video/Creator').ShopeeVideoTaskItem[]} taskList
 * @returns {Promise<import('@type/Shopee/Video/Creator').ShopeeVideoTaskResult[]>}
 */
export const editVideoTask = async (taskList) => {
  return creatorRequest(
    { method: 'POST', url: '/publish/pc/api/task/edit', data: { taskList } },
    { dataPath: 'data.taskList', errorMsg: 'EDIT_VIDEO_TASK_ERROR', defaultValue: [] },
  );
};

/**
 * @param {string[]} taskIdList
 * @returns {Promise<import('@type/Shopee/Video/Creator').ShopeeVideoTaskResult[]>}
 */
export const postVideoTask = async (taskIdList) => {
  return creatorRequest(
    { method: 'POST', url: '/publish/pc/api/task/post', data: { taskIdList } },
    { dataPath: 'data.taskList', errorMsg: 'POST_VIDEO_TASK_ERROR', defaultValue: [] },
  );
};

/**
 * @param {string} taskId
 * @param {string} step
 * @param {number} startTimestamp
 * @param {number} endTimestamp
 * @returns {Promise<any>}
 */
export const reportVideoTask = async (taskId, step, startTimestamp, endTimestamp) => {
  return creatorRequest(
    {
      method: 'POST',
      url: '/publish/pc/api/task/report',
      data: {
        taskId, step, startTimestamp, endTimestamp,
      },
    },
    { errorMsg: 'REPORT_VIDEO_TASK_ERROR', defaultValue: null },
  );
};

/**
 * @param {number} videoId
 * @returns {Promise<any>}
 */
export const deleteVideo = async (videoId) => {
  return creatorRequest(
    { method: 'POST', url: '/publish/pc/api/video/delete', data: { videoId: Number(videoId) } },
    { errorMsg: 'DELETE_VIDEO_ERROR', defaultValue: null },
  );
};

/**
 * @param {string|number} postId
 * @returns {Promise<import('@type/Shopee/Video/Creator').ShopeeVideoDetail|null>}
 */
export const getVideoDetail = async (postId) => {
  return creatorRequest(
    { method: 'GET', url: '/api/supply/sellercenter/video/detail', params: { postId } },
    {
      client: apiShopeeSeller,
      dataPath: 'data',
      errorMsg: 'GET_VIDEO_DETAIL_ERROR',
      defaultValue: null,
      errorContext: { postId },
    },
  );
};
