import db from '../config/database';
import { Currency } from '../models/Currency';

export class CurrencyRepository {
  async findAll(): Promise<Currency[]> {
    return await db('cf_currency').where({ is_active: true });
  }

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

  async findByCode(code: string): Promise<Currency | null> {
    return await db('cf_currency').where({ code, is_active: true }).first();
  }

  async findDefault(): Promise<Currency | null> {
    return await db('cf_currency').where({ is_default: true, is_active: true }).first();
  }

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

  async update(id: string, data: Partial<Omit<Currency, 'id' | 'created_at'>>): Promise<Currency | null> {
    await db('cf_currency').where({ id }).update({
      ...data,
      updated_at: new Date(),
    });
    return await this.findById(id);
  }

  async deactivate(id: string): Promise<Currency | null> {
    await db('cf_currency').where({ id }).update({
      is_active: false,
      updated_at: new Date(),
    });
    return await this.findById(id);
  }

  async setDefault(id: string): Promise<Currency | null> {
    // 先将所有货币的 is_default 设置为 false
    await db('cf_currency').update({ is_default: false });
    
    // 再将指定货币设置为默认
    await db('cf_currency').where({ id }).update({
      is_default: true,
      updated_at: new Date(),
    });
    
    return await this.findById(id);
  }

  async exists(code: string): Promise<boolean> {
    const count = await db('cf_currency').where({ code }).count('id as count').first();
    return count.count > 0;
  }
}

export default new CurrencyRepository();
