{{{
  exports({ to: app.modelPath('currency.ts') })
}}}
import { BaseModel, column } from '@adonisjs/lucid/orm'
import { DateTime } from 'luxon'

/**
 * Currency model for storing exchange rates
 */
export default class Currency extends BaseModel {
  public static table = 'currencies'

  @column({ isPrimary: true })
  declare id: number

  /**
   * Currency code (e.g., USD, EUR, GBP)
   */
  @column()
  declare code: string

  /**
   * Currency name (e.g., US Dollar, Euro)
   */
  @column()
  declare name: string

  /**
   * Currency symbol (e.g., $, €, £)
   */
  @column()
  declare symbol: string

  /**
   * Countries using this currency
   */
  @column({
    prepare: (value) => (typeof value === 'object' ? JSON.stringify(value) : value),
    consume: (value) => (typeof value === 'string' ? JSON.parse(value) : value),
  })
  declare countries: string[]

  /**
   * Exchange rate relative to base currency (e.g., USD)
   * For the base currency itself (e.g., USD), this should be 1.0
   */
  @column({
    columnName: 'exchange_rate',
    prepare: (value) => (typeof value === 'string' ? Number.parseFloat(value) : value),
    consume: (value) => (typeof value === 'string' ? Number.parseFloat(value) : value),
  })
  declare exchangeRate: number

  /**
   * Currency status (active/inactive)
   */
  @column()
  declare status: boolean

  @column.dateTime({ autoCreate: true })
  declare createdAt: DateTime

  @column.dateTime({ autoCreate: true, autoUpdate: true })
  declare updatedAt: DateTime

  /**
   * Get exchange rate for a specific currency pair
   * Logic: assumes all rates are relative to a common base (e.g., USD)
   */
  public static async getRate(from: string, to: string, baseCurrency: string = 'USD'): Promise<number | null> {
    if (from === to) return 1

    // Handle base currency conversions
    if (from === baseCurrency && to === baseCurrency) return 1

    if (from === baseCurrency) {
      const toRate = await this.query().where('code', to).first()
      return toRate ? toRate.exchangeRate : null
    }

    if (to === baseCurrency) {
      const fromRate = await this.query().where('code', from).first()
      return fromRate ? 1 / fromRate.exchangeRate : null
    }

    // Cross rate conversion
    const fromRate = await this.query().where('code', from).first()
    const toRate = await this.query().where('code', to).first()

    if (!fromRate || !toRate) {
      return null
    }

    // Calculate cross rate: to_rate / from_rate
    return toRate.exchangeRate / fromRate.exchangeRate
  }

  /**
   * Get all available exchange rates
   */
  public static async getAllRates() {
    const rates = await this.query().where('status', true)

    const result: Record<string, number> = {}
    for (const rate of rates) {
      result[rate.code] = rate.exchangeRate
    }

    return result
  }
}
