/**
 * Order Item Entity
 * Mecánicas Diesel - ERP Suite
 *
 * Represents line items (services or parts) in a service order.
 */

import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  ManyToOne,
  JoinColumn,
  Index,
} from 'typeorm';
import { ServiceOrder } from './service-order.entity';

export enum OrderItemType {
  SERVICE = 'service',
  PART = 'part',
}

export enum OrderItemStatus {
  PENDING = 'pending',
  IN_PROGRESS = 'in_progress',
  COMPLETED = 'completed',
}

@Entity({ name: 'order_items', schema: 'service_management' })
@Index('idx_order_items_order', ['orderId'])
export class OrderItem {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ name: 'order_id', type: 'uuid' })
  orderId: string;

  // Type
  @Column({ name: 'item_type', type: 'varchar', length: 20 })
  itemType: OrderItemType;

  // Optional references
  @Column({ name: 'service_id', type: 'uuid', nullable: true })
  serviceId?: string;

  @Column({ name: 'part_id', type: 'uuid', nullable: true })
  partId?: string;

  // Description
  @Column({ type: 'varchar', length: 500 })
  description: string;

  // Quantities and prices
  @Column({ type: 'decimal', precision: 10, scale: 3, default: 1 })
  quantity: number;

  @Column({ name: 'unit_price', type: 'decimal', precision: 12, scale: 2 })
  unitPrice: number;

  @Column({ name: 'discount_pct', type: 'decimal', precision: 5, scale: 2, default: 0 })
  discountPct: number;

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

  // Status
  @Column({
    type: 'varchar',
    length: 20,
    default: OrderItemStatus.PENDING,
  })
  status: OrderItemStatus;

  // For labor items
  @Column({ name: 'estimated_hours', type: 'decimal', precision: 5, scale: 2, nullable: true })
  estimatedHours?: number;

  @Column({ name: 'actual_hours', type: 'decimal', precision: 5, scale: 2, nullable: true })
  actualHours?: number;

  // Mechanic
  @Column({ name: 'performed_by', type: 'uuid', nullable: true })
  performedBy?: string;

  @Column({ name: 'completed_at', type: 'timestamptz', nullable: true })
  completedAt?: Date;

  @Column({ type: 'text', nullable: true })
  notes?: string;

  @Column({ name: 'sort_order', type: 'integer', default: 0 })
  sortOrder: number;

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

  // Relations
  @ManyToOne(() => ServiceOrder, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'order_id' })
  order: ServiceOrder;
}
