import { Injectable } from "@nestjs/common"
import { CreateContractorDto } from "./dto/create-contractor.dto"
import { UpdateContractorDto } from "./dto/update-contractor.dto"
import { ContractorFiltersDto } from "./dto/contractor-filters.dto"
import { ContractorRepository } from "./repositories/contractor.repository"
import { PartyTypesService } from "../party-types/party-types.service"
import { PartyTypeCategory } from "../party-types/entities/party-type.entity"
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 { Contractor } from "./entities/contractor.entity"
import { verifyJwtToken } from "src/utils/jwt"

@Injectable()
export class ContractorsService {
  constructor(
    private readonly contractorRepository: ContractorRepository,
    private readonly partyTypesService: PartyTypesService,
  ) {}

  // ==================== CONTRACTOR TYPES ====================

  async getTypes(token: string) {
    return this.partyTypesService.getTypesByCategory(
      PartyTypeCategory.CONTRACTOR,
      token,
    )
  }

  // ==================== CONTRACTORS ====================

  async create(createContractorDto: CreateContractorDto, token: string) {
    const decoded = verifyJwtToken(token)
    if (!decoded) {
      return failureResponse(
        code.VALIDATION,
        validationMessage(messageKey.invalid_token),
      )
    }

    // Check if contractor with same name exists for the company
    const existingContractor = await this.contractorRepository.getByParams({
      where: {
        company_id: decoded.company_id,
        contractor_name: createContractorDto.contractor_name,
      },
      findOne: true,
    })

    if (existingContractor) {
      return failureResponse(
        code.VALIDATION,
        validationMessage(messageKey.already_exist, {
          ":data": "Contractor",
          ":field": "contractor_name",
        }),
      )
    }

    let contractor: any = new Contractor()
    contractor = {
      ...createContractorDto,
      company_id: decoded.company_id,
      created_by: decoded.user_id,
    }

    await this.contractorRepository.save(contractor)

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

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

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

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

    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":
        case "contractor_name":
          orderBy = { contractor_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 (type_id) {
      whereConditions.type_id = type_id
    }

    if (project_id) {
      whereConditions.project_id = project_id
    }

    // Add search functionality for name, phone, and email
    if (search) {
      searchConditions.contractor_name = search
      searchConditions.phone_number = search
      searchConditions.email = search
    }

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

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

  async findOne(id: number) {
    const contractor: any = await this.contractorRepository.getByParams({
      where: { id },
      whereNull: ["deleted_at"],
      relations: [
        "company:id,name",
        "partyType:id,type_name",
        "project:id,name",
      ],
      findOne: true,
    })

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

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

  async update(
    id: number,
    updateContractorDto: UpdateContractorDto,
    token: string,
  ) {
    const decoded = verifyJwtToken(token)

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

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

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

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

      if (existingContractor) {
        return failureResponse(
          code.VALIDATION,
          validationMessage(messageKey.already_exist, {
            ":data": "Contractor",
            ":field": "contractor_name",
          }),
        )
      }
    }

    // Update the contractor
    Object.assign(contractor, updateContractorDto)
    contractor.updated_by = decoded.user_id
    await this.contractorRepository.save(contractor)

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

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

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

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

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

    await this.contractorRepository.remove({ id: contractor.id })

    await this.contractorRepository.save({
      id: contractor.id,
      deleted_by: decoded.user_id,
    })

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

  async checkContractorExist(name: string, companyId: number) {
    const contractor = await this.contractorRepository.getByParams({
      where: {
        contractor_name: name,
        company_id: companyId,
      },
      findOne: true,
    })

    return !isEmpty(contractor)
  }

  async checkContractorTypeExist(typeName: string, companyId: number) {
    return this.partyTypesService.checkPartyTypeExist(
      typeName,
      PartyTypeCategory.CONTRACTOR,
      companyId,
    )
  }
}
