import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
} from 'typeorm';
import { Currency } from './currency.entity';

export type RateSource = 'manual' | 'banxico' | 'xe' | 'openexchange';

@Entity({ schema: 'core', name: 'currency_rates' })
@Index('idx_currency_rates_tenant', ['tenantId'])
@Index('idx_currency_rates_from', ['fromCurrencyId'])
@Index('idx_currency_rates_to', ['toCurrencyId'])
@Index('idx_currency_rates_date', ['rateDate'])
@Index('idx_currency_rates_lookup', ['fromCurrencyId', 'toCurrencyId', 'rateDate'])
export class CurrencyRate {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ type: 'uuid', name: 'tenant_id', nullable: true })
  tenantId: string | null;

  @Column({ type: 'uuid', name: 'from_currency_id', nullable: false })
  fromCurrencyId: string;

  @ManyToOne(() => Currency)
  @JoinColumn({ name: 'from_currency_id' })
  fromCurrency: Currency;

  @Column({ type: 'uuid', name: 'to_currency_id', nullable: false })
  toCurrencyId: string;

  @ManyToOne(() => Currency)
  @JoinColumn({ name: 'to_currency_id' })
  toCurrency: Currency;

  @Column({ type: 'decimal', precision: 18, scale: 8, nullable: false })
  rate: number;

  @Column({ type: 'date', name: 'rate_date', nullable: false })
  rateDate: Date;

  @Column({ type: 'varchar', length: 50, default: 'manual' })
  source: RateSource;

  @Column({ type: 'uuid', name: 'created_by', nullable: true })
  createdBy: string | null;

  @CreateDateColumn({ name: 'created_at', type: 'timestamptz' })
  createdAt: Date;
}
