import { BadRequestException, ConflictException, ForbiddenException } from '@nestjs/common';
import { ActivityType, Prisma, UserRole, UserStatus } from '@prisma/client';
import { PrismaService } from '../../prisma/prisma.service';
import { RequestTenantContext, TenantQueryHelper } from '../tenancy/tenant-query.helper';

export const OWNER_NOT_IN_ORG = 'Choose an owner from your organization';

export interface CrmActor {
  id: string;
  role: UserRole;
  canDelete: boolean;
}

export type NoteEntityField = 'leadId' | 'contactId' | 'accountId' | 'dealId';

/** Ensures an optional owner ID refers to an active user in the same tenant. */
export async function assertTenantOwner(prisma: PrismaService, tenantId: string, ownerId: string | null | undefined): Promise<void> {
  if (!ownerId) return;
  const owner = await prisma.user.findFirst({
    where: { id: ownerId, tenantId, status: UserStatus.ACTIVE },
    select: { id: true },
  });
  if (!owner) throw new BadRequestException(OWNER_NOT_IN_ORG);
}

/** Org Admins may delete freely; Org Members require custom role or canDelete enabled by Admin. */
export function assertCanDelete(actor: CrmActor & { customRole?: { permissions?: Array<{ module: string; canDelete: boolean }> } }): void {
  if (actor.role === UserRole.ORGANIZATION_ADMIN) {
    return;
  }
  if (actor.customRole?.permissions) {
    return;
  }
  if (!actor.canDelete) {
    throw new ForbiddenException('Your organization admin has not allowed you to delete records');
  }
}

/** Converts Prisma foreign-key constraint errors (P2003) into a 409 conflict. */
export function rethrowRelationConflict(err: unknown, message: string): never {
  if (err instanceof Prisma.PrismaClientKnownRequestError && err.code === 'P2003') {
    throw new ConflictException(message);
  }
  throw err;
}

export async function listEntityNotes(prisma: PrismaService, tenant: TenantQueryHelper, ctx: RequestTenantContext, field: NoteEntityField, id: string) {
  const notes = await prisma.activity.findMany({
    where: tenant.scopeWhere(ctx, {
      [field]: id,
      type: ActivityType.NOTE,
    }),
    orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
    select: {
      id: true,
      description: true,
      createdAt: true,
      owner: { select: { id: true, name: true } },
    },
  });
  return notes.map((n) => ({
    id: n.id,
    body: n.description ?? '',
    author: n.owner,
    createdAt: n.createdAt,
  }));
}

export async function createEntityNote(prisma: PrismaService | Prisma.TransactionClient, tenant: TenantQueryHelper, ctx: RequestTenantContext, field: NoteEntityField, id: string, body: string) {
  const n = await prisma.activity.create({
    data: tenant.scopeCreate(ctx, {
      type: ActivityType.NOTE,
      title: 'Note',
      description: body,
      [field]: id,
      ownerId: ctx.userId,
    }),
    select: {
      id: true,
      description: true,
      createdAt: true,
      owner: { select: { id: true, name: true } },
    },
  });
  return {
    id: n.id,
    body: n.description ?? '',
    author: n.owner,
    createdAt: n.createdAt,
  };
}
