import { ORGANISATION_MEMBER_ROLE_PERMISSIONS_MAP } from '@documenso/lib/constants/organisations';
import { AppError, AppErrorCode } from '@documenso/lib/errors/app-error';
import { getMemberOrganisationRole } from '@documenso/lib/server-only/team/get-member-roles';
import { buildOrganisationWhereQuery, isOrganisationRoleWithinUserHierarchy } from '@documenso/lib/utils/organisations';
import { prisma } from '@documenso/prisma';
import { OrganisationGroupType } from '@prisma/client';

import { authenticatedProcedure } from '../trpc';
import {
  ZDeleteOrganisationGroupRequestSchema,
  ZDeleteOrganisationGroupResponseSchema,
} from './delete-organisation-group.types';

export const deleteOrganisationGroupRoute = authenticatedProcedure
  // .meta(deleteOrganisationGroupMeta)
  .input(ZDeleteOrganisationGroupRequestSchema)
  .output(ZDeleteOrganisationGroupResponseSchema)
  .mutation(async ({ input, ctx }) => {
    const { groupId, organisationId } = input;
    const { user } = ctx;

    ctx.logger.info({
      input: {
        groupId,
        organisationId,
      },
    });

    const organisation = await prisma.organisation.findFirst({
      where: buildOrganisationWhereQuery({
        organisationId,
        userId: user.id,
        roles: ORGANISATION_MEMBER_ROLE_PERMISSIONS_MAP['MANAGE_ORGANISATION'],
      }),
    });

    if (!organisation) {
      throw new AppError(AppErrorCode.UNAUTHORIZED);
    }

    const group = await prisma.organisationGroup.findFirst({
      where: {
        id: groupId,
        organisationId,
      },
    });

    if (!group) {
      throw new AppError(AppErrorCode.NOT_FOUND, {
        message: 'Organisation group not found',
      });
    }

    if (
      group.type === OrganisationGroupType.INTERNAL_ORGANISATION ||
      group.type === OrganisationGroupType.INTERNAL_TEAM
    ) {
      throw new AppError(AppErrorCode.UNAUTHORIZED, {
        message: 'You are not allowed to delete internal groups',
      });
    }

    const currentUserOrganisationRole = await getMemberOrganisationRole({
      organisationId,
      reference: {
        type: 'User',
        id: user.id,
      },
    });

    // A user cannot delete a group whose role is higher than their own
    // (e.g. a manager deleting an admin-role group).
    if (!isOrganisationRoleWithinUserHierarchy(currentUserOrganisationRole, group.organisationRole)) {
      throw new AppError(AppErrorCode.UNAUTHORIZED, {
        message: 'You are not allowed to delete this organisation group',
      });
    }

    await prisma.organisationGroup.delete({
      where: {
        id: groupId,
        organisationId: organisation.id,
      },
    });
  });
