import { Injectable } from '@nestjs/common';
import { CrmTraining } from '@prisma/client';
import { PrismaService } from '../../../../prisma/prisma.service';
import { EntityManager } from '../../core/entity-manager.base';
import { EntityEventsService } from '../../core/entity-events.service';
import { EntityContext } from '../../core/entity-context.interface';
import { TrainingPermissions } from './training.permissions';
import { TimelineService } from '../../services/timeline.service';

const TRAINING_INCLUDE = {
  deal: { select: { id: true, title: true, contactName: true } },
  trainer: { select: { id: true, firstName: true, lastName: true } },
};

@Injectable()
export class TrainingManager extends EntityManager<CrmTraining & { id: string }> {
  readonly entityType = 'training';
  readonly modelName = 'crmTraining';
  readonly include = TRAINING_INCLUDE;

  constructor(
    prisma: PrismaService,
    events: EntityEventsService,
    permissions: TrainingPermissions,
    private readonly timeline: TimelineService,
  ) {
    super(prisma, events, permissions);
  }

  protected async onAfterAdd(entity: any, context?: EntityContext): Promise<void> {
    // Timeline entry
    await this.timeline.addEntry(entity.dealId, context?.userId || null, 'TRAINING_CREATED', {
      subject: `Тренировка запланирована`,
      metadata: {
        trainingId: entity.id,
        type: entity.type,
        scheduledAt: entity.scheduledAt.toISOString(),
        clientName: entity.clientName,
      },
    });
  }

  protected async onAfterUpdate(
    entity: any,
    oldEntity: any,
    context?: EntityContext,
  ): Promise<void> {
    // Status change → timeline
    if (entity.status !== oldEntity.status) {
      const statusNames: Record<string, string> = {
        CRM_PLANNED: 'Запланирована',
        CRM_COMPLETED: 'Проведена',
        CRM_CANCELLED: 'Отменена',
        CRM_NO_SHOW: 'Клиент не пришёл',
      };
      await this.timeline.addEntry(entity.dealId, context?.userId || null, 'SYSTEM', {
        subject: `Тренировка: ${statusNames[entity.status] || entity.status}`,
        metadata: {
          trainingId: entity.id,
          oldStatus: oldEntity.status,
          newStatus: entity.status,
        },
      });
    }
  }
}
