import { Injectable, BadRequestException, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { CreateQuoteDto } from './dto/create-quote.dto';
import { UpdateQuoteDto } from './dto/update-quote.dto';
import { WhatsappService } from '../whatsapp/whatsapp.service';

@Injectable()
export class QuotesService {
  constructor(
    private readonly prisma: PrismaService,
    private readonly whatsappService: WhatsappService
  ) { }

  async create(createQuoteDto: CreateQuoteDto) {
    const quote = await this.prisma.quote.create({
      data: {
        ...createQuoteDto,
        items: JSON.stringify(createQuoteDto.items)
      } as any,
      include: {
        opportunity: {
          include: {
            client: true,
          },
        },
        enquiry: {
          include: {
            client: true,
          },
        },
      },
    });

    try {
      const client = quote.opportunity?.client || quote.enquiry?.client;
      console.log('Quote created. Attempting to send WhatsApp to client:', client?.name, 'Phone:', client?.phone);
      if (client) {
        const baseUrl = process.env.API_BASE_URL || 'http://localhost:3000';
        const mediaUrl = quote.pdfUrl ? `${baseUrl}${quote.pdfUrl}` : undefined;
        console.log('Calling whatsappService.sendQuoteCreation with mediaUrl:', mediaUrl);
        await this.whatsappService.sendQuoteCreation(
          client.phone,
          client.name,
          quote.totalAmount.toString(),
          mediaUrl
        );
      }
    } catch (err) {
      console.error('Failed to send quote creation WhatsApp:', err.message);
    }

    return quote;
  }

  findAll() {
    return this.prisma.quote.findMany({
      include: {
        opportunity: {
          include: {
            client: true,
          },
        },
        enquiry: {
          include: {
            client: true,
          },
        },
        user: true,
      },
    });
  }

  findOne(id: string) {
    return this.prisma.quote.findUnique({
      where: { id },
      include: {
        opportunity: {
          include: {
            client: true,
          },
        },
        enquiry: {
          include: {
            client: true,
          },
        },
        user: true,
      },
    });
  }

  update(id: string, updateQuoteDto: UpdateQuoteDto) {
    const data = { ...updateQuoteDto } as any;
    if (updateQuoteDto.items) {
      data.items = JSON.stringify(updateQuoteDto.items);
    }
    return this.prisma.quote.update({
      where: { id },
      data,
    });
  }

  remove(id: string) {
    return this.prisma.quote.delete({
      where: { id },
    });
  }

  async send(id: string, type: 'whatsapp' | 'email') {
    const quote = await this.findOne(id);
    
    if (!quote) {
      throw new NotFoundException(`Quote with ID ${id} not found`);
    }

    const client = quote.opportunity?.client || quote.enquiry?.client;
    
    if (!client) {
      throw new BadRequestException('This quote is not linked to a valid client');
    }
    
    if (!client.phone) {
      throw new BadRequestException('The client associated with this quote has no phone number');
    }

    const baseUrl = process.env.API_BASE_URL || 'http://localhost:3000';
    const mediaUrl = quote.pdfUrl ? `${baseUrl}${quote.pdfUrl}` : undefined;

    if (type === 'whatsapp') {
      const fs = require('fs');
      fs.appendFileSync('service_log.txt', `[${new Date().toISOString()}] Manual send triggered for ID: ${id}\n`);
      console.log('Manually sending quote via WhatsApp. ID:', id);
      const result = await this.whatsappService.sendQuote(
        client.phone,
        client.name,
        quote.totalAmount.toString(),
        mediaUrl
      );
      console.log('WhatsApp send result:', result);
      
      if (result && !(result as any).success) {
        throw new BadRequestException((result as any).error || 'Failed to send WhatsApp message');
      }
      
      return result;
    }
    
    return { success: true };
  }
}
