import { Request, Response } from 'express';

import * as invoiceService from '@/modules/invoice/invoice.service';
import catchAsync from '@/shared/utils/catchAsync';
import responseCodes from '@/shared/utils/responseCode/responseCode';
import { pick } from '@/shared/utils';

const { InvoiceResponseCodes } = responseCodes;

export const createInvoice = catchAsync(async (req: Request, res: Response) => {
  const shouldMerge = req.query.merge === 'true'; // ?merge=true
  const invoice = await invoiceService.createInvoice(req.body, shouldMerge);
  res.success(
    invoice,
    InvoiceResponseCodes.SUCCESS,
    'Invoice Created Successfully',
  );
});

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

  const updatedInvoice = await invoiceService.updateInvoice(id, req.body);
  res.success(
    updatedInvoice,
    InvoiceResponseCodes.SUCCESS,
    'Invoice Updated Successfully',
  );
});

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

    const invoice = await invoiceService.deleteInvoice(id);
    res.success(
      invoice,
      InvoiceResponseCodes.SUCCESS,
      'Invoice Deleted Successfully',
    );
  },
);

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

    const invoice = await invoiceService.getInvoiceById(id);
    res.success(
      invoice,
      InvoiceResponseCodes.SUCCESS,
      'Invoice Fetched Successfully',
    );
  },
);

export const getInvoices = catchAsync(async (req: Request, res: Response) => {
  const filter = pick(req.query, ['company', 'search', 'status', 'from', 'to']);
  const options = pick(req.query, [
    'sortBy',
    'limit',
    'page',
    'populate',
    'includeTimeStamps',
  ]);

  const invoices = await invoiceService.queryInvoices(filter, options);
  res.success(
    invoices,
    InvoiceResponseCodes.SUCCESS,
    'Invoices Fetched Successfully',
  );
});
