import type { HttpContext } from '@adonisjs/core/http'
import InternationalCity from '#models/international_city'
import { listAllValidator } from '#validators/international_cities'

export default class InternationalCitiesController {
  async listAll({ request, response }: HttpContext) {
    const {
      country_code: countryCode,
      country_id: countryId,
      search,
    } = await request.validateUsing(listAllValidator)

    const query = InternationalCity.query()

    if (countryCode) {
      query.where('country_code', countryCode)
    }

    if (countryId) {
      query.where('country_id', countryId)
    }

    if (search) {
      query.where('name', 'like', `%${search}%`)
    }

    const cities = await query.orderBy('name', 'asc').exec()

    return response.ok({
      status: true,
      message: 'Cities listed successfully',
      data: cities,
    })
  }

  async listAllByCustomer({ request, response }: HttpContext) {
    const {
      country_code: countryCode,
      country_id: countryId,
      search,
    } = await request.validateUsing(listAllValidator)

    const query = InternationalCity.query()

    if (countryCode) {
      query.where('country_code', countryCode)
    }

    if (countryId) {
      query.where('country_id', countryId)
    }

    if (search) {
      const keyword = search.trim().toLowerCase()

      // Filter
      query.whereRaw('LOWER(name) LIKE ?', [`%${keyword}%`])

      // Relevance ordering
      query.orderByRaw(
        `
      CASE
        WHEN LOWER(name) LIKE ? THEN 1
        WHEN LOWER(name) LIKE ? THEN 2
        ELSE 3
      END
      `,
        [`${keyword}%`, `%${keyword}%`]
      )
    }

    // Secondary alphabetical order
    query.orderBy('name', 'asc')

    const cities = await query

    return response.ok({
      status: true,
      message: 'Cities listed successfully',
      data: cities,
    })
  }

  async getByCountryCode({ params, response }: HttpContext) {
    const { country_code: countryCode } = params
    const cities = await InternationalCity.query()
      .where('country_code', countryCode)
      .orderBy('name', 'asc')
      .exec()
    return response.ok({
      status: true,
      message: 'Cities listed successfully',
      data: cities,
    })
  }
}
