import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Customer } from './customer.entity';
import { Repository } from 'typeorm';
import { RpcException } from '@nestjs/microservices';

@Injectable()
export class CustomerService {
  constructor(
    @InjectRepository(Customer)
    private customerRepo: Repository<Customer>,
  ) {}
  async getAll(): Promise<any> {
    const data = await this.customerRepo.find();
    return data;
  }

  async create(
    data: any,
    Salary_Slip: Express.Multer.File,
    NIC_Front: Express.Multer.File,
    NIC_Back: Express.Multer.File,
    Utility_Bill: Express.Multer.File,
    Photo: Express.Multer.File,
  ): Promise<any> {
    console.log('service also calling!');
    const customer = this.customerRepo.create({
      ...data,
      Salary_Slip_Path: Salary_Slip?.filename || '',
      NIC_Front_Path: NIC_Front?.filename || '',
      NIC_Back_Path: NIC_Back?.filename || '',
      Utility_Bill_Path: Utility_Bill?.filename || '',
      Photo_Path: Photo?.filename || '',
    });

    await this.customerRepo.save(customer);
    return { success: true, message: 'Customer created successfully' };
  }

  async getById(id: number) {
    const data = await this.customerRepo.findOneBy({ idCustomer: id });
    return data;
  }

  async update(
    id: number,
    data: any,
    Salary_Slip?: Express.Multer.File,
    NIC_Front?: Express.Multer.File,
    NIC_Back?: Express.Multer.File,
    Utility_Bill?: Express.Multer.File,
    Photo?: Express.Multer.File,
  ): Promise<any> {
    const existingCustomer = await this.customerRepo.findOneBy({
      idCustomer: id,
    });

    if (!existingCustomer) {
      throw new Error('Customer not found');
    }

    const updatedCustomer = this.customerRepo.merge(existingCustomer, {
      ...data,
      Salary_Slip_Path: Salary_Slip
        ? Salary_Slip.filename
        : existingCustomer.Salary_Slip_Path,
      NIC_Front_Path: NIC_Front
        ? NIC_Front.filename
        : existingCustomer.NIC_Front_Path,
      NIC_Back_Path: NIC_Back
        ? NIC_Back.filename
        : existingCustomer.NIC_Back_Path,
      Utility_Bill_Path: Utility_Bill
        ? Utility_Bill.filename
        : existingCustomer.Utility_Bill_Path,
      Photo_Path: Photo ? Photo.filename : existingCustomer.Photo_Path,
    });

    await this.customerRepo.save(updatedCustomer);

    return { success: true, message: 'Customer updated successfully' };
  }

  async getPendingVerification() {
    const data = await this.customerRepo.query(`SELECT *
FROM customer
WHERE 
  (
 (NIC_Back_Path IS NOT NULL AND NIC_Back_Path != '' AND NIC_Back_Verification_Status = '0') OR
    (Utility_Bill_Path IS NOT NULL AND Utility_Bill_Path != '' AND Utility_Bill_Verification_Status = '0') OR
     (NIC_Front_Path IS NOT NULL AND NIC_Front_Path != '' AND NIC_Front_Verification_Status = '0') OR
    (Photo_Path IS NOT NULL AND Photo_Path != '' AND Photo_Verification_Status = '0') OR
    (Salary_Slip_Path IS NOT NULL AND Salary_Slip_Path != '' AND Salary_Slip_Verification_Status = '0') 
  );
`);

    return data;
  }

  async getPendingVerificationByCustomerId(id: number) {
    const data = await this.customerRepo.query(`SELECT *
FROM customer
WHERE  idCustomer = ${id} AND 
  (
 (NIC_Back_Path IS NOT NULL AND NIC_Back_Path != '' AND NIC_Back_Verification_Status = '0') OR
    (Utility_Bill_Path IS NOT NULL AND Utility_Bill_Path != '' AND Utility_Bill_Verification_Status = '0') OR
     (NIC_Front_Path IS NOT NULL AND NIC_Front_Path != '' AND NIC_Front_Verification_Status = '0') OR
    (Photo_Path IS NOT NULL AND Photo_Path != '' AND Photo_Verification_Status = '0') OR
    (Salary_Slip_Path IS NOT NULL AND Salary_Slip_Path != '' AND Salary_Slip_Verification_Status = '0') 
  );
`);
    return data;
  }

  async verifyDocumentByName(id: number, fieldname: string, Status: string) {
    try {
      const query = `UPDATE customer SET ${fieldname} = ? WHERE idCustomer = ?`;
      const result = await this.customerRepo.query(query, [Status, id]);

      return { success: true, message: 'Status changed!' };
    } catch (err) {
      throw new RpcException(err.message || 'Internal server error');
    }
  }

  async getRejectedDocByCustomerId(idCustomer: number) {
    try {
      console.log(idCustomer);
      const query = `SELECT COUNT(*) AS count FROM customer WHERE idCustomer = ? AND (Salary_Slip_Verification_Status = 2 OR NIC_Front_Verification_Status = 2 OR NIC_Back_Verification_Status = 2 OR Utility_Bill_Verification_Status = 2 OR Photo_Verification_Status = 2)`;
      const result = await this.customerRepo.query(query, [idCustomer]);

      return result[0].count;
    } catch (err) {
      throw new RpcException(err.message || 'Internal server error');
    }
  }
}
