import {
  Injectable,
  NotFoundException,
  ConflictException,
  BadRequestException,
} from "@nestjs/common";

import { CustomersRepository } from "./customers.repository";
import { CreateCustomerDto } from "./dto/create-customer.dto";
import { UpdateCustomerDto } from "./dto/update-customer.dto";
import { Customer } from "./entities/customer.entity";

@Injectable()
export class CustomersService {
  constructor(private readonly customersRepository: CustomersRepository) {}

  /** Create a new customer */
  async create(dto: CreateCustomerDto): Promise<Customer> {
    const exists = await this.customersRepository.existsByUniqueFields(
      dto.email,
      dto.vatNumber,
    );

    if (exists) {
      throw new ConflictException(
        "Customer with same email or VAT number already exists",
      );
    }

    if (dto.vatNumber && dto.vatNumber.length !== 10) {
      throw new BadRequestException("VAT number must be exactly 10 digits");
    }

    return this.customersRepository.create(dto);
  }

  /** Get all customers */
  findAll(): Promise<Customer[]> {
    return this.customersRepository.findAll({
      order: { companyName: "ASC" },
    });
  }

  /** Get customer by ID */
  async findById(id: string): Promise<Customer> {
    const customer = await this.customersRepository.findById(id);

    if (!customer) {
      throw new NotFoundException(`Customer with ID ${id} not found`);
    }

    return customer;
  }

  // async findByUserId(userId: string): Promise<Customer> {
  //   const customer = await this.customersRepository.findByUserId(userId);
     
  //   if (!customer) {
  //     throw new NotFoundException(`Customer with ID ${userId} not found`);
  //   }

   // return customer;
  //}

  /** Get customer by email */
  async findByEmail(email: string): Promise<Customer> {
    const customer = await this.customersRepository.findByEmail(email);

    if (!customer) {
      throw new NotFoundException(`Customer with email ${email} not found`);
    }

    return customer;
  }

  /** Get customer by VAT number */
  async findByVatNumber(vatNumber: string): Promise<Customer> {
    const customer = await this.customersRepository.findByVatNumber(vatNumber);

    if (!customer) {
      throw new NotFoundException(
        `Customer with VAT number ${vatNumber} not found`,
      );
    }

    return customer;
  }

  /** Search customers by name */
  searchByName(name: string): Promise<Customer[]> {
    return this.customersRepository.findByName(name);
  }

  /** Update customer */
  async update(id: string, dto: UpdateCustomerDto): Promise<Customer> {
    await this.findById(id);

    // Validate VAT number if provided
    if (dto.vatNumber && dto.vatNumber.length !== 10) {
      throw new BadRequestException("VAT number must be exactly 10 digits");
    }

    // // Check email conflict
    // if (dto.email) {
    //   const existing = await this.customersRepository.findByEmail(dto.email);

    //  // if (existing && existing.userId !== id) {
    //   //  throw new ConflictException(
    //   //    `Customer with email "${dto.email}" already exists`,
    //   //  );
    //  // }
    // }

    const updated = await this.customersRepository.update(id, dto);

    if (!updated) {
      throw new NotFoundException(`Customer ${id} not found`);
    }

    return updated;
  }

  /** Delete customer (soft delete) */
  async remove(id: string): Promise<void> {
    await this.findById(id);
    await this.customersRepository.softDelete(id);
  }

  /** Get customer statistics */
  async getStats(): Promise<{ total: number; withVatNumber: number }> {
    const total = await this.customersRepository.count();
    const withVatNumber = await this.customersRepository.countWithVatNumber();

    return { total, withVatNumber };
  }

  delete(id: string): any {
    return id;
  }
}