import { Entity, Column, Index, ManyToOne, JoinColumn } from 'typeorm';
import { BaseEntity } from '../database/base.entity';
import { TaxTypeEntity } from './tax-type.entity';
import { DestinationEntity } from './destination.entity';

/**
 * TaxSlab — per-destination tax configuration for a given TaxType.
 *
 * Per stakeholder spec: tax NAME + component STRUCTURE live on the
 * TaxType master. The slab attaches a specific destination to that
 * structure and fills in the RATE for each component.
 *
 * `component_rates` is a jsonb dict `{ [component_id]: rate }` —
 * e.g. for a Goa/India GST slab:
 *   {
 *     "<cgst-component-id>": 9,
 *     "<sgst-component-id>": 9,
 *   }
 * The service recomputes `total_rate` from the rate sum on write
 * so reports + line-item snapshots can read the total without
 * re-aggregating.
 *
 * Unique on (tenant × tax_type × destination) — one slab per combo.
 */
@Entity('tax_slabs')
@Index(['tenant_id', 'tax_type_id', 'destination_id'], {
  unique: true,
  where: '"is_deleted" = false',
})
export class TaxSlabEntity extends BaseEntity {
  @ManyToOne(() => TaxTypeEntity, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'tax_type_id' })
  tax_type: TaxTypeEntity;

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

  @ManyToOne(() => DestinationEntity, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'destination_id' })
  destination: DestinationEntity;

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

  /** Total effective rate — recomputed from component_rates on save. */
  @Column({ type: 'decimal', precision: 5, scale: 2, default: 0 })
  total_rate: number;

  /**
   * Per-component rates as `{ [tax_component_id]: rate }`. jsonb so
   * the shape evolves with the TaxType's component list without
   * requiring a migration per component change.
   */
  @Column({ type: 'jsonb', nullable: true })
  component_rates: Record<string, number> | null;

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

  @Column({ type: 'boolean', default: true })
  is_active: boolean;
}
