import { Injectable } from "@nestjs/common"
import { CreateClientDto } from "./dto/create-client.dto"
import { UpdateClientDto } from "./dto/update-client.dto"
import { ClientRepository } from "./repositories/client.repository"
import {
  errorMessage,
  isEmpty,
  successMessage,
  validationMessage,
} from "../../utils/helpers"
import {
  failureResponse,
  successResponse,
} from "../../common/response/response"
import { code } from "../../common/response/response.code"
import { messageKey } from "../../constants/message-keys"
import { Client } from "./entities/client.entity"
import { verifyJwtToken } from "src/utils/jwt"

@Injectable()
export class ClientsService {
  constructor(private readonly clientRepository: ClientRepository) {}

  async create(createClientDto: CreateClientDto, token: string) {
    const decoded = verifyJwtToken(token)

    if (!decoded) {
      return failureResponse(
        code.VALIDATION,
        validationMessage(messageKey.invalid_token),
      )
    }

    // Check if client with same name exists for the company
    const existingClient = await this.clientRepository.getByParams({
      where: {
        company_id: decoded.company_id,
        name: createClientDto.name,
      },
      findOne: true,
    })

    if (existingClient) {
      return failureResponse(
        code.VALIDATION,
        validationMessage(messageKey.already_exist, {
          ":data": "Client",
          ":field": "name",
        }),
      )
    }

    let client: any = new Client()
    client = {
      ...createClientDto,
      status: createClientDto.status || 1,
      company_id: decoded.company_id,
      created_by: decoded.user_id,
    }

    await this.clientRepository.save(client)

    return successResponse(
      code.SUCCESS,
      successMessage(messageKey.data_add, { ":data": "Client" }),
    )
  }

  async findAll(query: any = {}, token: string) {
    const decoded = verifyJwtToken(token)

    if (!decoded) {
      return failureResponse(
        code.VALIDATION,
        validationMessage(messageKey.invalid_token),
      )
    }
    const {
      page = 1,
      limit = 10,
      search,
      status,
      column_name,
      order = "DESC",
    } = query

    const skip = (page - 1) * limit
    const take = parseInt(limit)

    const orderDirection = isEmpty(order) ? "DESC" : order.toUpperCase()

    // Set up dynamic ordering
    let orderBy: any = { created_at: orderDirection }

    if (!isEmpty(column_name)) {
      switch (column_name) {
        case "name":
          orderBy = { name: orderDirection }
          break
        case "created_at":
        default:
          orderBy = { created_at: orderDirection }
          break
      }
    }

    const whereConditions: any = {}
    const searchConditions: any = {}

    // Add filters
    if (decoded.company_id) {
      whereConditions.company_id = decoded.company_id
    }

    if (status) {
      whereConditions.status = status
    }

    // Add search functionality
    if (search) {
      searchConditions.name = search
    }

    const clients: any = await this.clientRepository.getByParams({
      where: whereConditions,
      search: !isEmpty(searchConditions) ? searchConditions : undefined,
      relations: ["company:id,name"],
      orderBy,
      take,
      skip,
    })

    return successResponse(
      code.SUCCESS,
      successMessage(messageKey.data_retrieve, { ":data": "Clients" }),
      clients,
    )
  }

  async findOne(id: number) {
    const client: any = await this.clientRepository.getByParams({
      where: { id },
      whereNull: ["deleted_at"],
      relations: ["company:id,name"],
      findOne: true,
    })

    if (isEmpty(client)) {
      return failureResponse(
        code.VALIDATION,
        errorMessage(messageKey.data_not_found, { ":data": "Client" }),
      )
    }

    return successResponse(
      code.SUCCESS,
      successMessage(messageKey.data_retrieve, { ":data": "Client" }),
      client,
    )
  }

  async update(id: number, updateClientDto: UpdateClientDto, token: string) {
    const decoded = verifyJwtToken(token)

    if (!decoded) {
      return failureResponse(
        code.VALIDATION,
        validationMessage(messageKey.invalid_token),
      )
    }

    const client: any = await this.clientRepository.getByParams({
      where: { id },
      findOne: true,
    })

    if (isEmpty(client)) {
      return failureResponse(
        code.VALIDATION,
        errorMessage(messageKey.data_not_found, { ":data": "Client" }),
      )
    }

    // Check if client with same name exists for the company (excluding current record)
    if (updateClientDto.name) {
      const existingClient = await this.clientRepository.getByParams({
        where: {
          company_id: decoded.company_id,
          name: updateClientDto.name,
        },
        whereNull: ["deleted_at"],
        whereNotIn: { id: [id] },
        findOne: true,
      })

      if (existingClient) {
        return failureResponse(
          code.VALIDATION,
          validationMessage(messageKey.already_exist, {
            ":data": "Client",
            ":field": "name",
          }),
        )
      }
    }

    // Update the client
    Object.assign(client, updateClientDto)
    client.updated_by = decoded.user_id
    await this.clientRepository.save(client)

    return successResponse(
      code.SUCCESS,
      successMessage(messageKey.data_update, { ":data": "Client" }),
    )
  }

  async remove(id: number, token: string) {
    const decoded = verifyJwtToken(token)

    if (!decoded) {
      return failureResponse(
        code.VALIDATION,
        validationMessage(messageKey.invalid_token),
      )
    }

    const client: any = await this.clientRepository.getByParams({
      where: { id },
      whereNull: ["deleted_at"],
      findOne: true,
    })

    if (isEmpty(client)) {
      return failureResponse(
        code.VALIDATION,
        errorMessage(messageKey.data_not_found, { ":data": "Client" }),
      )
    }

    await this.clientRepository.remove({ id: client.id })

    await this.clientRepository.save({
      id: client.id,
      deleted_by: decoded.user_id,
    })

    return successResponse(
      code.SUCCESS,
      successMessage(messageKey.data_removed, { ":data": "Client" }),
    )
  }

  async activeInactive(id: number, token: string) {
    const decoded = verifyJwtToken(token)

    if (!decoded) {
      return failureResponse(
        code.VALIDATION,
        validationMessage(messageKey.invalid_token),
      )
    }

    const client: any = await this.clientRepository.getByParams({
      where: { id, company_id: decoded.company_id },
      findOne: true,
    })

    if (isEmpty(client)) {
      return failureResponse(
        code.VALIDATION,
        errorMessage(messageKey.data_not_found, { ":data": "Client" }),
      )
    }

    client.status = client.status === 1 ? 0 : 1
    client.updated_by = decoded.user_id

    await this.clientRepository.save(client)

    return successResponse(
      code.SUCCESS,
      successMessage(messageKey.data_update, { ":data": "Client" }),
    )
  }

  async checkClientExist(name: string, companyId: number) {
    const client = await this.clientRepository.getByParams({
      where: {
        name: name,
        company_id: companyId,
      },
      findOne: true,
    })

    return !isEmpty(client)
  }
}
