import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { ActivityType, Prisma } from '@prisma/client';
import { PrismaService } from '../../prisma/prisma.service';
import { RequestTenantContext, TenantQueryHelper } from '../../common/tenancy/tenant-query.helper';
import { assertCanDelete, assertTenantOwner, rethrowRelationConflict, type CrmActor } from '../../common/crm/crm-record.helper';
import { CreateActivityDto } from './dto/create-activity.dto';
import { UpdateActivityDto } from './dto/update-activity.dto';
import { ListActivitiesQuery } from './dto/list-activities.query';

const NOT_FOUND = 'Activity not found';

export const activitySelect = {
  id: true,
  type: true,
  title: true,
  description: true,
  outcome: true,
  durationMinutes: true,
  performedAt: true,
  dueDate: true,
  ownerId: true,
  leadId: true,
  contactId: true,
  accountId: true,
  dealId: true,
  createdAt: true,
  updatedAt: true,
  owner: { select: { id: true, name: true, email: true } },
  lead: { select: { id: true, name: true, company: true } },
  contact: { select: { id: true, name: true, email: true } },
  account: { select: { id: true, name: true } },
  deal: { select: { id: true, title: true, dealNumber: true } },
} satisfies Prisma.ActivitySelect;

@Injectable()
export class ActivitiesService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly tenant: TenantQueryHelper,
  ) {}

  // Returns paginated activities matching type, owner, entity, and text filters.
  async list(ctx: RequestTenantContext, q: ListActivitiesQuery) {
    const page = Math.max(1, q.page ?? 1);
    const limit = Math.min(100, Math.max(1, q.limit ?? 50));
    const skip = (page - 1) * limit;

    const where: Prisma.ActivityWhereInput = this.tenant.scopeWhere(ctx, {
      ...(q.type && q.type !== 'all' ? { type: q.type as ActivityType } : {}),
      ...(q.ownerId ? { ownerId: q.ownerId } : {}),
      ...(q.leadId ? { leadId: q.leadId } : {}),
      ...(q.contactId ? { contactId: q.contactId } : {}),
      ...(q.accountId ? { accountId: q.accountId } : {}),
      ...(q.dealId ? { dealId: q.dealId } : {}),
      ...(q.q
        ? {
            OR: [{ title: { contains: q.q } }, { description: { contains: q.q } }, { outcome: { contains: q.q } }],
          }
        : {}),
    });

    const [items, total] = await Promise.all([
      this.prisma.activity.findMany({
        where,
        select: activitySelect,
        orderBy: [{ performedAt: 'desc' }, { id: 'desc' }],
        skip,
        take: limit,
      }),
      this.prisma.activity.count({ where }),
    ]);

    return {
      data: items,
      meta: {
        total,
        page,
        limit,
        totalPages: Math.ceil(total / limit) || 1,
      },
    };
  }

  // Retrieves an activity record by ID within tenant scope.
  async get(ctx: RequestTenantContext, id: string) {
    const act = await this.prisma.activity.findFirst({
      where: this.tenant.scopeWhere(ctx, { id }),
      select: activitySelect,
    });
    if (!act) throw new NotFoundException(NOT_FOUND);
    return act;
  }

  // Creates a new activity associated with CRM entities.
  async create(ctx: RequestTenantContext, dto: CreateActivityDto) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    await assertTenantOwner(this.prisma, tenantId, dto.ownerId);

    try {
      return await this.prisma.activity.create({
        data: this.tenant.scopeCreate(ctx, {
          type: dto.type,
          title: dto.title.trim(),
          description: dto.description?.trim() || null,
          outcome: dto.outcome?.trim() || null,
          durationMinutes: dto.durationMinutes ?? null,
          performedAt: dto.performedAt ? new Date(dto.performedAt) : new Date(),
          dueDate: dto.dueDate ? new Date(dto.dueDate) : null,
          ownerId: dto.ownerId ?? ctx.userId,
          leadId: dto.leadId ?? null,
          contactId: dto.contactId ?? null,
          accountId: dto.accountId ?? null,
          dealId: dto.dealId ?? null,
        }),
        select: activitySelect,
      });
    } catch (err) {
      rethrowRelationConflict(err, 'Linked record does not exist');
    }
  }

  // Updates an existing activity record within tenant scope.
  async update(ctx: RequestTenantContext, id: string, dto: UpdateActivityDto) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    await this.get(ctx, id);
    if (dto.ownerId) {
      await assertTenantOwner(this.prisma, tenantId, dto.ownerId);
    }

    try {
      return await this.prisma.activity.update({
        where: { tenantId_id: { tenantId, id } },
        data: {
          ...(dto.type && { type: dto.type }),
          ...(dto.title !== undefined && { title: dto.title.trim() }),
          ...(dto.description !== undefined && {
            description: dto.description?.trim() || null,
          }),
          ...(dto.outcome !== undefined && {
            outcome: dto.outcome?.trim() || null,
          }),
          ...(dto.durationMinutes !== undefined && {
            durationMinutes: dto.durationMinutes,
          }),
          ...(dto.performedAt && { performedAt: new Date(dto.performedAt) }),
          ...(dto.dueDate !== undefined && {
            dueDate: dto.dueDate ? new Date(dto.dueDate) : null,
          }),
          ...(dto.ownerId !== undefined && { ownerId: dto.ownerId }),
          ...(dto.leadId !== undefined && { leadId: dto.leadId }),
          ...(dto.contactId !== undefined && { contactId: dto.contactId }),
          ...(dto.accountId !== undefined && { accountId: dto.accountId }),
          ...(dto.dealId !== undefined && { dealId: dto.dealId }),
        },
        select: activitySelect,
      });
    } catch (err) {
      rethrowRelationConflict(err, 'Linked record does not exist');
    }
  }

  // Deletes an activity record within tenant scope.
  async remove(ctx: RequestTenantContext, actor: CrmActor, id: string) {
    const tenantId = this.tenant.getRequiredTenantId(ctx);
    assertCanDelete(actor);
    await this.get(ctx, id);
    await this.prisma.activity.delete({
      where: { tenantId_id: { tenantId, id } },
    });
    return { success: true };
  }

  // Retrieves chronological activity timeline for an entity.
  async timeline(ctx: RequestTenantContext, entityType: 'lead' | 'contact' | 'account' | 'deal', entityId: string) {
    const fieldMap: Record<string, string> = {
      lead: 'leadId',
      contact: 'contactId',
      account: 'accountId',
      deal: 'dealId',
    };
    const field = fieldMap[entityType];
    if (!field) throw new BadRequestException('Invalid entity type');

    const activities = await this.prisma.activity.findMany({
      where: this.tenant.scopeWhere(ctx, { [field]: entityId }),
      select: activitySelect,
      orderBy: [{ performedAt: 'desc' }, { id: 'desc' }],
      take: 100,
    });

    return activities;
  }
}
