import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { CreateTargetDto } from './dto/create-target.dto';
import { UpdateTargetDto } from './dto/update-target.dto';
import { NotificationsService } from '../notifications/notifications.service';

@Injectable()
export class TargetsService {
  constructor(
    private prisma: PrismaService,
    private notifications: NotificationsService,
  ) {}

  async create(createTargetDto: CreateTargetDto) {
    const { monthlyTarget, avgDealValue: providedAvgDealValue } = createTargetDto;
    
    // Logic for auto-calculation
    const avgDealValue = providedAvgDealValue || 40000;
    const weeklyTarget = monthlyTarget / 4;
    
    const requiredClosures = createTargetDto.requiredClosures ?? Math.ceil(monthlyTarget / avgDealValue);
    const requiredDemos = createTargetDto.requiredDemos ?? (requiredClosures * 3);
    const requiredPotential = createTargetDto.requiredPotential ?? (requiredDemos * 2);
    const requiredQualityLeads = requiredPotential * 5;
    const requiredLeads = createTargetDto.requiredLeads ?? (requiredQualityLeads * 2);
    const dailyLeadTarget = createTargetDto.dailyLeadTarget ?? Math.ceil(requiredLeads / 25);

    const target = await this.prisma.target.create({
      data: {
        ...createTargetDto,
        weeklyTarget,
        dailyLeadTarget,
        requiredLeads,
        requiredPotential,
        requiredDemos,
        requiredClosures,
        closureRatio: 0.33,
        avgDealValue,
      } as any,
    });

    // 🔔 Notify the user their target has been set
    const monthName = new Date(createTargetDto.year, createTargetDto.month - 1).toLocaleString('default', { month: 'long', year: 'numeric' });
    await this.notifications.create(
      createTargetDto.userId,
      '🎯 New Target Assigned',
      `Your ${monthName} target has been set: ₹${(monthlyTarget / 100000).toFixed(1)}L monthly, with ${dailyLeadTarget} leads/day required.`,
      'TARGET',
      { targetId: target.id, monthlyTarget, minTarget: createTargetDto.minTarget, requiredClosures, requiredDemos, dailyLeadTarget },
    );

    return target;
  }

  async findAll() {
    return this.prisma.target.findMany({
      include: { user: { select: { name: true, email: true } } },
    });
  }

  async findByUser(userId: string) {
    return this.prisma.target.findMany({
      where: { userId },
      orderBy: { year: 'desc', month: 'desc' },
    });
  }

  async findOne(id: string) {
    return this.prisma.target.findUnique({
      where: { id },
      include: { user: true },
    });
  }

  async update(id: string, updateTargetDto: UpdateTargetDto) {
    const current = await this.prisma.target.findUnique({ where: { id } });
    if (!current) return null;

    const monthlyTarget = updateTargetDto.monthlyTarget ?? current.monthlyTarget;
    const avgDealValue = updateTargetDto.avgDealValue ?? current.avgDealValue ?? 40000;
    
    const weeklyTarget = monthlyTarget / 4;
    const requiredClosures = updateTargetDto.requiredClosures ?? Math.ceil(monthlyTarget / avgDealValue);
    const requiredDemos = updateTargetDto.requiredDemos ?? (requiredClosures * 3);
    const requiredPotential = updateTargetDto.requiredPotential ?? (requiredDemos * 2);
    const requiredQualityLeads = requiredPotential * 5;
    const requiredLeads = updateTargetDto.requiredLeads ?? (requiredQualityLeads * 2);
    const dailyLeadTarget = updateTargetDto.dailyLeadTarget ?? Math.ceil(requiredLeads / 25);

    const updated = await this.prisma.target.update({
      where: { id },
      data: {
        ...updateTargetDto,
        weeklyTarget,
        dailyLeadTarget,
        requiredLeads,
        requiredPotential,
        requiredDemos,
        requiredClosures,
        closureRatio: 0.33,
        avgDealValue,
      } as any,
    });

    // 🔔 Notify user their target was updated
    const monthName = new Date(current.year, current.month - 1).toLocaleString('default', { month: 'long', year: 'numeric' });
    await this.notifications.create(
      current.userId,
      '🔄 Target Revised',
      `Your ${monthName} target has been updated: ₹${(monthlyTarget / 100000).toFixed(1)}L monthly, ${dailyLeadTarget} leads/day required.`,
      'TARGET_UPDATE',
      { targetId: id, monthlyTarget, requiredClosures, requiredDemos, dailyLeadTarget },
    );

    return updated;
  }

  async remove(id: string) {
    return this.prisma.target.delete({ where: { id } });
  }
}
