import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, Index, OneToMany } from 'typeorm';
import { SettlementItem } from './settlement-item.entity';

@Entity('settlements')
@Index('uk_settlement_no', ['settlementNo'], { unique: true })
@Index('idx_merchant_id', ['merchantId'])
@Index('idx_period_start', ['periodStart'])
@Index('idx_status', ['status'])
export class Settlement {
  @PrimaryGeneratedColumn({ type: 'bigint', unsigned: true, comment: '结算单ID' })
  id: number;

  @Column({ type: 'varchar', length: 32, name: 'settlement_no', comment: '结算单号' })
  settlementNo: string;

  @Column({ type: 'bigint', unsigned: true, name: 'merchant_id', comment: '商家ID' })
  merchantId: number;

  @Column({ type: 'date', name: 'period_start', comment: '结算周期开始日期' })
  periodStart: string;

  @Column({ type: 'date', name: 'period_end', comment: '结算周期结束日期' })
  periodEnd: string;

  @Column({ type: 'int', unsigned: true, default: 0, name: 'order_count', comment: '订单数量' })
  orderCount: number;

  @Column({ type: 'decimal', precision: 12, scale: 2, default: 0, name: 'order_amount', comment: '订单总额' })
  orderAmount: number;

  @Column({ type: 'decimal', precision: 12, scale: 2, default: 0, name: 'service_fee', comment: '服务费总额' })
  serviceFee: number;

  @Column({ type: 'decimal', precision: 12, scale: 2, default: 0, name: 'settlement_amount', comment: '结算金额（订单总额-服务费）' })
  settlementAmount: number;

  @Column({ type: 'enum', enum: ['pending', 'settled', 'failed'], default: 'pending', comment: '状态' })
  status: 'pending' | 'settled' | 'failed';

  @Column({ type: 'datetime', nullable: true, name: 'settled_at', comment: '结算时间' })
  settledAt: Date;

  @Column({ type: 'varchar', length: 500, nullable: true, comment: '备注' })
  remark: string;

  @OneToMany(() => SettlementItem, item => item.settlement)
  items: SettlementItem[];

  @CreateDateColumn({ type: 'datetime', name: 'created_at', comment: '创建时间' })
  createdAt: Date;

  @UpdateDateColumn({ type: 'datetime', name: 'updated_at', comment: '更新时间' })
  updatedAt: Date;
}
