import { Injectable, Logger } from '@nestjs/common';
import { PrismaService } from '../../../prisma/prisma.service';

/**
 * Bridge between Telegram Bot module and CRM module.
 * Creates deals from bot scenarios when action type = 'crm_deal'.
 */
@Injectable()
export class CrmIntegrationService {
  private readonly logger = new Logger(CrmIntegrationService.name);

  constructor(private readonly prisma: PrismaService) {}

  /**
   * Create a CRM deal from bot scenario data.
   * Uses DealManager pattern (direct Prisma for now to avoid circular deps).
   */
  async createDeal(
    clubId: string,
    fields: {
      title?: string;
      contactName?: string;
      contactPhone?: string;
      contactEmail?: string;
      contactTelegram?: string;
      pipelineId?: string;
      source?: string;
      metadata?: Record<string, unknown>;
    },
  ): Promise<{ id: string; number: number } | null> {
    try {
      // Get default pipeline if not specified
      let pipelineId = fields.pipelineId;
      let stageId: string | undefined;

      if (!pipelineId) {
        const defaultPipeline = await this.prisma.crmPipeline.findFirst({
          where: { clubId, entityType: 'deal' },
          orderBy: { createdAt: 'asc' },
        });

        if (!defaultPipeline) {
          this.logger.warn(`No CRM pipeline found for club ${clubId}, skipping deal creation`);
          return null;
        }
        pipelineId = defaultPipeline.id;

        const firstStage = await this.prisma.crmStage.findFirst({
          where: { pipelineId, type: 'OPEN' },
          orderBy: { position: 'asc' },
        });
        stageId = firstStage?.id;
      }

      if (!stageId) {
        const stage = await this.prisma.crmStage.findFirst({
          where: { pipelineId, type: 'OPEN' },
          orderBy: { position: 'asc' },
        });
        stageId = stage?.id;
      }

      if (!stageId) {
        this.logger.warn(`No open stage found in pipeline ${pipelineId}`);
        return null;
      }

      // Generate sequential number
      const maxNumber = await this.prisma.crmDeal.aggregate({
        where: { clubId },
        _max: { number: true },
      });
      const nextNumber = (maxNumber._max.number ?? 0) + 1;

      const deal = await this.prisma.crmDeal.create({
        data: {
          clubId,
          pipelineId,
          stageId,
          number: nextNumber,
          title: fields.title ?? `TG Bot: ${fields.contactName ?? 'Новая заявка'}`,
          contactName: fields.contactName ?? 'Из Telegram-бота',
          contactPhone: fields.contactPhone ?? null,
          contactEmail: fields.contactEmail ?? null,
          contactTelegram: fields.contactTelegram ?? null,
          source: 'WEBHOOK',
          metadata: (fields.metadata ?? {}) as object,
        },
        select: { id: true, number: true },
      });

      // Add timeline entry
      await this.prisma.crmTimeline.create({
        data: {
          dealId: deal.id,
          type: 'FORM_SUBMISSION',
          subject: 'Заявка из Telegram-бота',
          content: 'Создано автоматически из сценария бота.',
          metadata: { source: 'telegram_bot' },
        },
      });

      this.logger.log(`CRM deal #${deal.number ?? 0} created for club ${clubId} from TG bot`);
      return { id: deal.id, number: deal.number ?? 0 };
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : String(err);
      this.logger.error(`Failed to create CRM deal: ${msg}`);
      return null;
    }
  }
}
