import type { NextApiRequest, NextApiResponse } from 'next';
import { jsonRes } from '@fastgpt/service/common/response';
import { getDownloadStream, getFileById } from '@fastgpt/service/common/file/gridfs/controller';
import { CommonErrEnum } from '@fastgpt/global/common/error/code/common';
import { stream2Encoding } from '@fastgpt/service/common/file/gridfs/utils';
import { authFileToken } from '@fastgpt/service/support/permission/auth/file';
import { isS3ObjectKey } from '@fastgpt/service/common/s3/utils';
import { getS3DatasetSource } from '@fastgpt/service/common/s3/sources/dataset';

const previewableExtensions = [
  'jpg',
  'jpeg',
  'png',
  'gif',
  'bmp',
  'webp',
  'txt',
  'log',
  'csv',
  'md',
  'json'
];
export default async function handler(req: NextApiRequest, res: NextApiResponse<any>) {
  try {
    const { token, filename } = req.query as { token: string; filename: string };

    const { fileId, bucketName } = await authFileToken(token);

    if (!fileId) {
      throw new Error('fileId is empty');
    }

    const [file, fileStream] = await (() => {
      if (isS3ObjectKey(fileId, 'dataset')) {
        return Promise.all([
          getS3DatasetSource().getFileMetadata(fileId),
          getS3DatasetSource().getDatasetFileStream(fileId)
        ]);
      }

      return Promise.all([
        getFileById({ bucketName, fileId }),
        getDownloadStream({ bucketName, fileId })
      ]);
    })();

    if (!file) {
      return Promise.reject(CommonErrEnum.fileNotFound);
    }

    const { stream, encoding } = await (async () => {
      if ('metadata' in file && file.metadata?.encoding) {
        return {
          stream: fileStream,
          encoding: file.metadata.encoding
        };
      }
      return stream2Encoding(fileStream);
    })();

    const extension = file.filename.split('.').pop() || '';
    const disposition = previewableExtensions.includes(extension) ? 'inline' : 'attachment';

    res.setHeader('Content-Type', `${file.contentType}; charset=${encoding}`);
    res.setHeader('Cache-Control', 'public, max-age=31536000');
    res.setHeader(
      'Content-Disposition',
      `${disposition}; filename="${encodeURIComponent(filename)}"`
    );
    res.setHeader('Content-Length', 'contentLength' in file ? file.contentLength : file.length);

    stream.pipe(res);

    stream.on('error', () => {
      res.status(500).end();
    });
    stream.on('end', () => {
      res.end();
    });
  } catch (error) {
    jsonRes(res, {
      code: 500,
      error
    });
  }
}
export const config = {
  api: {
    responseLimit: '100mb'
  }
};
