import { Response, NextFunction } from 'express';
import httpStatus from 'http-status';
import { PayloadRequest } from '../../express/types';
import { SanitizedGlobalConfig } from '../config/types';
import { Document } from '../../types';

export type UpdateGlobalResult = Promise<Response<Document> | void>;
export type UpdateGlobalResponse = (req: PayloadRequest, res: Response, next: NextFunction) => UpdateGlobalResult;

function update(globalConfig: SanitizedGlobalConfig): UpdateGlobalResponse {
  async function handler(req: PayloadRequest, res: Response, next: NextFunction) {
    try {
      const { slug } = globalConfig;
      const draft = req.query.draft === 'true';
      const autosave = req.query.autosave === 'true';

      const result = await this.operations.globals.update({
        req,
        globalConfig,
        slug,
        depth: req.query.depth,
        data: req.body,
        draft,
        autosave,
      });

      let message = 'Saved successfully.';

      if (draft) message = 'Draft saved successfully.';
      if (autosave) message = 'Autosaved successfully.';

      return res.status(httpStatus.OK).json({ message, result });
    } catch (error) {
      return next(error);
    }
  }

  const updateHandler = handler.bind(this);
  return updateHandler;
}

export default update;
