import {
  Column,
  CreateDateColumn,
  Entity,
  Index,
  PrimaryColumn,
  UpdateDateColumn,
} from 'typeorm';
import type { SourceType } from '../../third-party/entities/category.entity';

export type PaymentStatus =
  | 'unpaid'
  | 'paying'
  | 'paid'
  | 'pay_failed'
  | 'closed'
  | 'refunding'
  | 'refunded'
  | 'partial_refunded';

export type FulfillmentStatus =
  | 'pending'
  | 'submitting'
  | 'submitted'
  | 'processing'
  | 'completed'
  | 'failed'
  | 'canceled';

@Entity('orders')
@Index('uk_orders_order_no', ['orderNo'], { unique: true })
@Index('idx_orders_user_created', ['userId', 'createdAt'])
@Index('idx_orders_status_created', [
  'paymentStatus',
  'fulfillmentStatus',
  'createdAt',
])
export class Order {
  @PrimaryColumn({ type: 'varchar', length: 36 })
  id: string;

  @Column({ name: 'order_no', type: 'varchar', length: 40 })
  orderNo: string;

  @Column({ name: 'user_id', type: 'varchar', length: 36 })
  userId: string;

  @Column({ name: 'source_type', type: 'varchar', length: 32 })
  sourceType: SourceType;

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

  @Column({ name: 'total_amount', type: 'decimal', precision: 10, scale: 2 })
  totalAmount: string;

  @Column({ name: 'payable_amount', type: 'decimal', precision: 10, scale: 2 })
  payableAmount: string;

  @Column({
    name: 'paid_amount',
    type: 'decimal',
    precision: 10,
    scale: 2,
    default: 0,
  })
  paidAmount: string;

  @Column({ name: 'payment_status', type: 'varchar', length: 32 })
  paymentStatus: PaymentStatus;

  @Column({ name: 'fulfillment_status', type: 'varchar', length: 32 })
  fulfillmentStatus: FulfillmentStatus;

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

  @Column({ name: 'paid_at', type: 'datetime', nullable: true })
  paidAt: Date | null;

  @Column({ name: 'closed_at', type: 'datetime', nullable: true })
  closedAt: Date | null;

  @CreateDateColumn({ name: 'created_at', type: 'datetime', precision: 6 })
  createdAt: Date;

  @UpdateDateColumn({ name: 'updated_at', type: 'datetime', precision: 6 })
  updatedAt: Date;
}
