import db from '../config/database';
import { ExchangeRate, ExchangeRateHistory } from '../models/ExchangeRate';

export class ExchangeRateRepository {
  async findByCurrencies(fromCurrency: string, toCurrency: string): Promise<ExchangeRate | null> {
    return await db('cf_exchange_rate')
      .where({ from_currency: fromCurrency, to_currency: toCurrency })
      .first();
  }

  async findAll(): Promise<ExchangeRate[]> {
    return await db('cf_exchange_rate');
  }

  async findById(id: string): Promise<ExchangeRate | null> {
    return await db('cf_exchange_rate').where({ id }).first();
  }

  async create(rate: Omit<ExchangeRate, 'id' | 'created_at' | 'updated_at'>): Promise<ExchangeRate> {
    const [id] = await db('cf_exchange_rate').insert(rate);
    return await this.findById(id);
  }

  async update(fromCurrency: string, toCurrency: string, data: Partial<Omit<ExchangeRate, 'id' | 'from_currency' | 'to_currency' | 'created_at'>>): Promise<ExchangeRate | null> {
    await db('cf_exchange_rate')
      .where({ from_currency: fromCurrency, to_currency: toCurrency })
      .update({
        ...data,
        updated_at: new Date(),
      });
    return await this.findByCurrencies(fromCurrency, toCurrency);
  }

  async upsert(rate: Omit<ExchangeRate, 'id' | 'created_at' | 'updated_at'>): Promise<ExchangeRate> {
    const existing = await this.findByCurrencies(rate.from_currency, rate.to_currency);
    if (existing) {
      return await this.update(rate.from_currency, rate.to_currency, rate);
    } else {
      return await this.create(rate);
    }
  }

  async delete(fromCurrency: string, toCurrency: string): Promise<number> {
    return await db('cf_exchange_rate')
      .where({ from_currency: fromCurrency, to_currency: toCurrency })
      .del();
  }

  // 汇率历史记录相关方法
  async createHistory(history: Omit<ExchangeRateHistory, 'id' | 'created_at'>): Promise<ExchangeRateHistory> {
    const [id] = await db('cf_exchange_rate_history').insert(history);
    return await this.findHistoryById(id);
  }

  async findHistoryById(id: string): Promise<ExchangeRateHistory | null> {
    return await db('cf_exchange_rate_history').where({ id }).first();
  }

  async findHistoryByDateRange(fromCurrency: string, toCurrency: string, startDate: Date, endDate: Date): Promise<ExchangeRateHistory[]> {
    return await db('cf_exchange_rate_history')
      .where({ from_currency: fromCurrency, to_currency: toCurrency })
      .where('date', '>=', startDate)
      .where('date', '<=', endDate)
      .orderBy('date', 'asc');
  }

  async findLatestHistory(fromCurrency: string, toCurrency: string): Promise<ExchangeRateHistory | null> {
    return await db('cf_exchange_rate_history')
      .where({ from_currency: fromCurrency, to_currency: to_currency })
      .orderBy('date', 'desc')
      .first();
  }

  async existsHistory(fromCurrency: string, toCurrency: string, date: Date): Promise<boolean> {
    const count = await db('cf_exchange_rate_history')
      .where({ from_currency: fromCurrency, to_currency: to_currency, date })
      .count('id as count')
      .first();
    return count.count > 0;
  }
}

export default new ExchangeRateRepository();
