import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, JoinColumn, Check } from 'typeorm';
import { Module } from './module.entity';
import { License } from './license.entity';
import { WebstoreSubscription } from './webstore-subscription.entity';

@Entity('payment_orders')
@Check(`"status" IN ('pending', 'completed', 'failed', 'refunded')`)
export class PaymentOrder {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ type: 'varchar', length: 255, unique: true })
  order_id: string;

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

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

  @Column({ type: 'uuid' })
  license_id: string;

  @Column({ type: 'decimal', precision: 10, scale: 2 })
  amount: number;

  @Column({ type: 'varchar', length: 3, default: 'USD' })
  currency: string;

  @Column({ type: 'varchar', length: 50 })
  status: string;

  @Column({ type: 'varchar', length: 255, nullable: true })
  transaction_id: string | null;

  @Column({ type: 'varchar', length: 255, nullable: true })
  payer_email: string | null;

  @Column({ type: 'timestamptz', default: () => 'NOW()' })
  created_at: Date;

  @Column({ type: 'timestamptz', nullable: true })
  completed_at: Date | null;

  @Column({ type: 'jsonb', nullable: true })
  metadata: Record<string, any> | null;

  @ManyToOne(() => Module, { onDelete: 'SET NULL', nullable: true })
  @JoinColumn({ name: 'module_id' })
  module: Module | null;

  @ManyToOne(() => License, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'license_id' })
  license: License;

  @ManyToOne(() => WebstoreSubscription, { onDelete: 'SET NULL', nullable: true })
  @JoinColumn({ name: 'webstore_subscription_id' })
  webstore_subscription: WebstoreSubscription | null;
}
