import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
} from 'typeorm';
import { LeaveType } from './leave-type.entity';

/**
 * Leave Allocation Entity (schema: hr.leave_allocations)
 *
 * Tracks allocated leave days per employee and leave type.
 * Supports period-based allocations with used/remaining tracking.
 *
 * Note: days_remaining is a computed column in PostgreSQL
 *
 * RLS Policy: tenant_id = current_setting('app.current_tenant_id')
 */
@Entity({ name: 'leave_allocations', schema: 'hr' })
export class LeaveAllocation {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Index()
  @Column({ name: 'tenant_id', type: 'uuid' })
  tenantId: string;

  @Index()
  @Column({ name: 'employee_id', type: 'uuid' })
  employeeId: string;

  // Note: ManyToOne to Employee removed - construction Employee
  // has a different structure and does not have leaveAllocations back-reference.

  @Index()
  @Column({ name: 'leave_type_id', type: 'uuid' })
  leaveTypeId: string;

  @ManyToOne(() => LeaveType, (leaveType) => leaveType.allocations, {
    onDelete: 'CASCADE',
  })
  @JoinColumn({ name: 'leave_type_id' })
  leaveType: LeaveType;

  @Column({ name: 'days_allocated', type: 'decimal', precision: 5, scale: 2 })
  daysAllocated: number;

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

  /**
   * Generated column in PostgreSQL: days_allocated - days_used
   * Mark as insert: false, update: false since it's computed by DB
   */
  @Column({
    name: 'days_remaining',
    type: 'decimal',
    precision: 5,
    scale: 2,
    insert: false,
    update: false,
    nullable: true,
  })
  daysRemaining: number;

  @Index()
  @Column({ name: 'date_from', type: 'date' })
  dateFrom: Date;

  @Column({ name: 'date_to', type: 'date' })
  dateTo: Date;

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

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

  @UpdateDateColumn({ name: 'updated_at', type: 'timestamptz' })
  updatedAt: Date;
}
