import { Injectable } from '@nestjs/common';
import { Context, Markup } from 'telegraf';
import { PrismaService } from '../../common/services/prisma.service';
import { AiService } from 'src/ai/ai.service';
import { QUESTIONS } from '../../common/constants/questions.constants';
import TEASER_MESSAGES from 'src/common/constants/teaser.constant';

@Injectable()
export class TestService {
  private userStates = new Map<string, any>();

  constructor(
    private prisma: PrismaService,
    private aiService: AiService,
  ) { }

  async createTest(userId: number) {
    return await this.prisma.test.create({
      data: { userId, answers: {} },
    });
  }

  setUserState(telegramId: string, state: any) {
    this.userStates.set(telegramId, state);
  }

  getUserState(telegramId: string) {
    return this.userStates.get(telegramId);
  }

  deleteUserState(telegramId: string) {
    this.userStates.delete(telegramId);
  }

  async sendQuestion(ctx: Context, questionIndex: number) {
    const keyboard = questionIndex > 0
      ? {
        reply_markup: Markup.inlineKeyboard([
          [Markup.button.callback('⏮ ویرایش سوال قبلی', `edit_${questionIndex - 1}`)]
        ]).reply_markup
      }
      : undefined;

    await ctx.reply(
      `سوال ${questionIndex + 1} از ${QUESTIONS.length}:\n\n${QUESTIONS[questionIndex]}\n\nلطفا پاسخ خود را تایپ کنید:`,
      { ...keyboard, protect_content: true }
    );
  }

  async updateTestAnswer(testId: number, questionIndex: number, answer: string) {
    const test = await this.prisma.test.findUnique({ where: { id: testId } });
    if (!test) return null;

    const answers = test.answers as any || {};
    answers[questionIndex] = answer;

    return await this.prisma.test.update({
      where: { id: testId },
      data: { answers, currentStep: questionIndex + 1 },
    });
  }

  async completeTest(ctx: Context, testId: number) {
    const test = await this.prisma.test.findUnique({ where: { id: testId } });
    if (!test) return;

    await this.prisma.test.update({
      where: { id: testId },
      data: { completedAt: new Date() },
    });

    const randomIndex = Math.floor(Math.random() * TEASER_MESSAGES.length);
    const teaserMessage = `${TEASER_MESSAGES[randomIndex]}
برای دریافت مشاوره کامل توسط تیم متخصصین ما هزینه ویزیت آنلاین و بررسی علمی و تخصصی پرسشنامه خود و تحلیل کامل رو بپردازید 👨‍⚕️📋
    
    `;
    await ctx.reply(
      `✅ تمام سوالات تکمیل شد!\n\n${teaserMessage}\n\nبرای مشاهده تحلیل کامل روی دکمه زیر کلیک کنید:`,
      Markup.inlineKeyboard([[Markup.button.callback('📊 دریافت نتیجه', 'get_result')]])
    );
  }
  async updateTestResult(testId: number, result: string) {
    return await this.prisma.test.update({
      where: { id: testId },
      data: { result },
    });
  }
  splitMessage(text: string, maxLength: number = 2000): string[] {
    if (text.length <= maxLength) return [text];

    const chunks: string[] = [];
    let currentChunk = '';
    const sentences = text.split('\n');

    for (const sentence of sentences) {
      if ((currentChunk + sentence + '\n').length <= maxLength) {
        currentChunk += sentence + '\n';
      } else {
        if (currentChunk) chunks.push(currentChunk.trim());
        currentChunk = sentence + '\n';
      }
    }

    if (currentChunk) chunks.push(currentChunk.trim());
    return chunks;
  }
}
