import { buildChannelPath, buildVODPath } from 'mweb/common/utils/pathBuilders';
import {
  fetchLiveToVODStatus,
  GO_TO_CHANNEL_STATUS,
  GO_TO_VOD_STATUS,
} from 'mweb/common/fetch/liveToVODStatus';
import { RedirectResponse } from 'mweb/lambda';
import { StatusCode } from 'mweb/common/reducers/root';
import {
  buildCacheControlHeader,
  PageExpiry,
} from 'mweb/server/selectors/cache';

export const STREAM_ID_QUERY_PARAMETER = 'stream_id';

export async function redirectForLiveToVOD(
  channelID: string,
  streamID: string,
): Promise<RedirectResponse> {
  const result = await fetchLiveToVODStatus(channelID, streamID);
  switch (result.status) {
    case GO_TO_VOD_STATUS:
      return {
        statusCode: StatusCode.PERMANENT_REDIRECT,
        headers: {
          location: buildVODPath(result.vod.id),
          cacheControl: buildCacheControlHeader(PageExpiry.LTV_TO_VOD),
        },
      };
    case GO_TO_CHANNEL_STATUS:
      const channelPath = buildChannelPath(result.channel);
      return {
        statusCode: StatusCode.TEMPORARY_REDIRECT,
        headers: {
          location: `${channelPath}?${STREAM_ID_QUERY_PARAMETER}=${streamID}`,
          cacheControl: buildCacheControlHeader(PageExpiry.LTV_TO_LIVE),
        },
      };
    default:
      throw {
        errorMessage: 'Unexpected liveToVODStatus status.',
        channelID,
        streamID,
        result,
      };
  }
}
