import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
} from 'typeorm';

/**
 * Account Mapping Entity
 *
 * Maps document types and operations to GL accounts.
 * Used by GL Posting Service to automatically create journal entries.
 *
 * Example mappings:
 * - Customer Invoice -> AR Account (debit), Sales Revenue (credit)
 * - Supplier Invoice -> AP Account (credit), Expense Account (debit)
 * - Payment Received -> Cash Account (debit), AR Account (credit)
 */
export enum AccountMappingType {
  CUSTOMER_INVOICE = 'customer_invoice',
  SUPPLIER_INVOICE = 'supplier_invoice',
  CUSTOMER_PAYMENT = 'customer_payment',
  SUPPLIER_PAYMENT = 'supplier_payment',
  SALES_REVENUE = 'sales_revenue',
  PURCHASE_EXPENSE = 'purchase_expense',
  TAX_PAYABLE = 'tax_payable',
  TAX_RECEIVABLE = 'tax_receivable',
  INVENTORY_ASSET = 'inventory_asset',
  COST_OF_GOODS_SOLD = 'cost_of_goods_sold',
}

@Entity({ name: 'account_mappings', schema: 'financial' })
@Index('idx_account_mappings_tenant_id', ['tenantId'])
@Index('idx_account_mappings_company_id', ['companyId'])
@Index('idx_account_mappings_type', ['mappingType'])
@Index('idx_account_mappings_unique', ['tenantId', 'companyId', 'mappingType'], { unique: true })
export class AccountMapping {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

  @Index()
  @Column({ name: 'company_id', type: 'uuid' })
  companyId: string;

  @Column({ name: 'mapping_type', type: 'varchar', length: 50 })
  mappingType: AccountMappingType | string;

  @Column({ name: 'account_id', type: 'uuid' })
  accountId: string;

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

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

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

  @Column({ name: 'created_by', type: 'uuid', nullable: true })
  createdBy: string | null;

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

  @Column({ name: 'updated_by', type: 'uuid', nullable: true })
  updatedBy: string | null;
}
