import { Request, Response } from 'express';

import * as teamService from '@/modules/teams/teams.service';
import catchAsync from '@/shared/utils/catchAsync';
import responseCodes from '@/shared/utils/responseCode/responseCode';
import { pick } from '@/shared/utils';
import { ApiError } from '@/shared/utils/errors';
import { defaultStatus } from '@/shared/utils/responseCode/httpStatusAlias';

const { TeamResponseCodes } = responseCodes;

export const createTeam = catchAsync(async (req: Request, res: Response) => {
  const team = await teamService.createTeam(req.body);
  res.success(team, TeamResponseCodes.SUCCESS, 'Team Created Successfully');
});

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

  const updatedTeam = await teamService.updateTeam(id, req.body);
  res.success(
    updatedTeam,
    TeamResponseCodes.SUCCESS,
    'Team Updated Successfully',
  );
});

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

    const team = await teamService.deleteTeam(id);
    res.success(team, TeamResponseCodes.SUCCESS, 'Team Deleted Successfully');
  },
);

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

  const teams = await teamService.getTeamById(id, req.user);

  res.success(
    teams,
    TeamResponseCodes.SUCCESS,
    'Team Fetched Successfully',
  );
});

export const getTeams = catchAsync(async (req: Request, res: Response) => {
  const companyId = req.user?.company?.id?.toString();
  if (!companyId)
    throw new ApiError(
      defaultStatus.BAD_REQUEST,
      'Company is required',
      true,
    );

  const { search } = pick(req.query, ['search']);
  const options = pick(req.query, [
    'sortBy',
    'limit',
    'page',
    'populate',
    'includeTimeStamps',
  ]);

  const teams = await teamService.queryTeams(
    { companyId, ...(search && { search }) },
    options,
    req.user,
  );

  res.success(
    teams,
    TeamResponseCodes.SUCCESS,
    'Team Fetched Successfully',
  );
});
