import { Request, Response } from 'express';

import * as timelineService from '@/modules/project/timeline/timeline.service';
import catchAsync from '@/shared/utils/catchAsync';
import responseCodes from '@/shared/utils/responseCode/responseCode';
import { pick } from '@/shared/utils';

const { TimelineResponseCodes } = responseCodes;

export const createTimeline = catchAsync(
  async (req: Request, res: Response) => {
    const { projectId } = req.params;
    console.log('🚀 ~ projectId:', projectId);
    const timelineData = { ...req.body, project: projectId };
    const result = await timelineService.createTimeline(timelineData);
    res.success(
      result,
      TimelineResponseCodes.SUCCESS,
      'Timeline Created Successfully',
    );
  },
);

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

    const result = await timelineService.updateTimeline(id, updateData);
    res.success(
      result,
      TimelineResponseCodes.SUCCESS,
      'Timeline Updated Successfully',
    );
  },
);

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

    const result = await timelineService.deleteTimeline(id);
    res.success(
      result,
      TimelineResponseCodes.SUCCESS,
      'Timeline Deleted Successfully',
    );
  },
);

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

    const result = await timelineService.getTimelineById(id);
    res.success(
      result,
      TimelineResponseCodes.SUCCESS,
      'Timeline Fetched Successfully',
    );
  },
);

export const getTimelines = catchAsync(async (req: Request, res: Response) => {
  const { projectId } = req.params;
  const filter = {
    ...pick(req.query, ['status', 'search', 'startDate', 'endDate', 'year']),
    project: projectId,
  };
  const options = pick(req.query, [
    'sortBy',
    'limit',
    'page',
    'populate',
    'includeTimeStamps',
  ]);

  const result = await timelineService.queryTimelines(filter, options);
  res.success(
    result,
    TimelineResponseCodes.SUCCESS,
    'Timelines Fetched Successfully',
  );
});
