import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, MoreThan } from 'typeorm';
import { Customer } from '../entities/customer.entity';
import { Order } from '../entities/order.entity';
import { CreateCustomerDto } from '../dto/create-customer.dto';
import { UpdateCustomerDto } from '../dto/update-customer.dto';

@Injectable()
export class CustomerService {
  constructor(
    @InjectRepository(Customer)
    private customerRepository: Repository<Customer>,
    @InjectRepository(Order)
    private orderRepository: Repository<Order>,
  ) {}

  async findAll(): Promise<Customer[]> {
    return this.customerRepository.find({
      relations: ['orders'],
      order: {
        createdAt: 'DESC',
      },
    });
  }

  async findOne(id: string): Promise<Customer> {
    return this.customerRepository.findOne({
      where: { id },
      relations: ['orders'],
    });
  }

  async create(createDto: CreateCustomerDto): Promise<Customer> {
    const customer = this.customerRepository.create(createDto);
    return this.customerRepository.save(customer);
  }

  async update(id: string, updateDto: UpdateCustomerDto): Promise<Customer> {
    await this.customerRepository.update(id, updateDto);
    return this.findOne(id);
  }

  async remove(id: string): Promise<void> {
    await this.customerRepository.delete(id);
  }

  async getCustomerOrders(customerId: string): Promise<Order[]> {
    return this.orderRepository.find({
      where: { customerId },
      relations: ['items'],
      order: {
        createdAt: 'DESC',
      },
    });
  }

  async getCustomerStats(): Promise<any> {
    const [totalCustomers, activeCustomers] = await Promise.all([
      this.customerRepository.count(),
      this.customerRepository.count({
        where: {
          isActive: true,
        },
      }),
    ]);

    const totalOrders = await this.orderRepository.count();
    const totalRevenue = await this.orderRepository
      .createQueryBuilder('order')
      .select('SUM(order.totalAmount)', 'total')
      .getRawOne();

    return {
      totalCustomers,
      activeCustomers,
      totalOrders,
      totalRevenue: totalRevenue.total,
    };
  }

  async getTopCustomers(limit: number = 10): Promise<any[]> {
    return this.customerRepository
      .createQueryBuilder('customer')
      .leftJoinAndSelect('customer.orders', 'order')
      .select(['customer.id', 'customer.name', 'customer.email'])
      .addSelect('COUNT(order.id)', 'orderCount')
      .addSelect('SUM(order.totalAmount)', 'totalSpent')
      .groupBy('customer.id')
      .orderBy('totalSpent', 'DESC')
      .limit(limit)
      .getRawMany();
  }

  // Additional methods for controller compatibility
  async findByStatus(status: string): Promise<Customer[]> {
    return this.customerRepository.find({
      where: { isActive: status === 'active' },
      relations: ['orders'],
    });
  }

  async search(term: string): Promise<Customer[]> {
    return this.customerRepository
      .createQueryBuilder('customer')
      .where('customer.name ILIKE :term OR customer.email ILIKE :term', { term: `%${term}%` })
      .getMany();
  }

  async createContactInquiry(contactData: any): Promise<void> {
    // Store contact inquiry in database
    // This could be stored in a separate contact_inquiries table
    console.log('Contact inquiry received:', contactData);
  }

  async createQuoteRequest(quoteData: any): Promise<void> {
    // Store quote request in database
    // This could be stored in a separate quote_requests table
    console.log('Quote request received:', quoteData);
  }

  async subscribeNewsletter(email: string): Promise<void> {
    // Add to newsletter subscription list
    // This could be stored in a separate newsletter_subscriptions table
    console.log('Newsletter subscription:', email);
  }
}
