import { Request, Response } from 'express';

import * as supportService from '@/modules/support/support.service';
import catchAsync from '@/shared/utils/catchAsync';
import responseCodes from '@/shared/utils/responseCode/responseCode';
import { pick } from '@/shared/utils';
import { SupportStatus } from '@/shared/constants/enum.constant';

const { SupportResponseCodes } = responseCodes;

export const createSupport = catchAsync(async (req: Request, res: Response) => {
  const { id: userId, company } = req.user;
  const companyId = company?.id;

  const supportPayload = {
    ...req.body,
    userId,
    companyId,
  };

  const support = await supportService.createSupport(supportPayload);

  return res.success(
    support,
    SupportResponseCodes.SUCCESS,
    'Support Created Successfully',
  );
});

export const updateSupport = catchAsync(async (req: Request, res: Response) => {
  const { id } = pick(req.params, ['id']);
  req.body.repliedAt = new Date();
  req.body.status = SupportStatus.REPLIED;

  const updatedSupport = await supportService.updateSupport(id, req.body);
  res.success(
    updatedSupport,
    SupportResponseCodes.SUCCESS,
    'Support Updated Successfully',
  );
});

export const getSupportById = catchAsync(
  async (req: Request, res: Response) => {
    const { id } = pick(req.params, ['id']);

    const Support = await supportService.getSupportById(id);

    res.success(
      Support,
      SupportResponseCodes.SUCCESS,
      'Support Fetched Successfully',
    );
  },
);

export const getSupport = catchAsync(async (req: Request, res: Response) => {
  const filter = pick(req.query, ['companyId', 'userId', 'search', 'status']);
  const options = pick(req.query, [
    'sortBy',
    'limit',
    'page',
    'fields',
    'includeTimeStamps',
  ]);

  const Support = await supportService.querySupport(filter, options);

  res.success(
    Support,
    SupportResponseCodes.SUCCESS,
    'Support Fetched Successfully',
  );
});
