import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, Index } from 'typeorm';

export type RewardType = 'CREDIT' | 'PERCENTAGE';
export type TriggerType = 'FIRST_PAYMENT' | 'RECURRING';
export type RewardStatus = 'PENDING' | 'APPLIED' | 'EXPIRED';

@Entity({ name: 'referral_rewards', schema: 'public' })
export class ReferralReward {
  @PrimaryGeneratedColumn('uuid')
  id!: string;

  // The tenant that receives the reward
  @Column({ name: 'beneficiary_tenant_id', type: 'varchar' })
  @Index()
  beneficiaryTenantId!: string;

  // Which referral relationship triggered this reward
  @Column({ name: 'referral_relationship_id', type: 'varchar' })
  referralRelationshipId!: string;

  // CREDIT: fixed USD cents amount
  @Column({ name: 'reward_type', type: 'varchar', length: 20 })
  rewardType!: RewardType;

  // FIRST_PAYMENT: one-time on first payment
  // RECURRING: each subsequent monthly payment (max 12 months)
  @Column({ name: 'trigger_type', type: 'varchar', length: 20 })
  triggerType!: TriggerType;

  // Reward amount in USD cents (e.g. 1500 = $15.00)
  @Column({ name: 'amount_cents', type: 'int' })
  amountCents!: number;

  // PENDING: waiting to be applied to next invoice
  // APPLIED: deducted from an invoice
  // EXPIRED: unused past expiry
  @Column({ type: 'varchar', length: 20, default: 'PENDING' })
  @Index()
  status!: RewardStatus;

  // The invoice this credit was applied to (set when status → APPLIED)
  @Column({ name: 'invoice_id', type: 'varchar', nullable: true })
  invoiceId!: string | null;

  // The invoice that triggered this reward (payment event source)
  @Column({ name: 'source_invoice_id', type: 'varchar', nullable: true })
  sourceInvoiceId!: string | null;

  // For recurring rewards: which month this covers (1-12)
  @Column({ name: 'recurring_month', type: 'int', nullable: true })
  recurringMonth!: number | null;

  @Column({ name: 'expires_at', type: 'timestamptz', nullable: true })
  expiresAt!: Date | null;

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

  @Column({ name: 'applied_at', type: 'timestamptz', nullable: true })
  appliedAt!: Date | null;
}
