import {
  Column,
  CreateDateColumn,
  Entity,
  Index,
  PrimaryColumn,
  UpdateDateColumn,
} from 'typeorm';
import type { FulfillmentStatus } from './order.entity';

export type FulfillmentType = 'third_party_api' | 'local_only' | 'manual';

@Entity('order_fulfillments')
@Index('idx_order_fulfillments_order_id', ['orderId'])
@Index('idx_order_fulfillments_status', ['status', 'createdAt'])
export class OrderFulfillment {
  @PrimaryColumn({ type: 'varchar', length: 36 })
  id: string;

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

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

  @Column({ name: 'fulfillment_type', type: 'varchar', length: 40 })
  fulfillmentType: FulfillmentType;

  @Column({ type: 'varchar', length: 32 })
  status: FulfillmentStatus;

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

  @Column({ name: 'external_order_no', type: 'varchar', length: 160, nullable: true })
  externalOrderNo: string | null;

  @Column({ name: 'request_payload', type: 'json', nullable: true })
  requestPayload: Record<string, unknown> | null;

  @Column({ name: 'response_payload', type: 'json', nullable: true })
  responsePayload: unknown | null;

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

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

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

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

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