/**
 * vendors — vendors-suppliers (wave-11 leaf-E).
 *
 * Vendor/supplier master table. Plain btree indexes declared via Drizzle.
 * Partial UNIQUE index on (tenant_id, tax_id WHERE tax_id IS NOT NULL)
 * and partial index on expenses.vendor_id are raw SQL in migration.
 */
import { pgTable, uuid, text, boolean, numeric, integer, date, timestamp, index } from 'drizzle-orm/pg-core'
import { tenants } from './tenants'

export const vendors = pgTable(
  'vendors',
  {
    id: uuid('id').primaryKey().defaultRandom(),
    tenantId: uuid('tenant_id')
      .notNull()
      .references(() => tenants.id, { onDelete: 'cascade' }),
    name: text('name').notNull(),
    taxId: text('tax_id'), // ח.פ. / ע.מ.
    // NULL = statutory default; 0 = exempt with valid cert
    withholdingRate: numeric('withholding_rate', { precision: 5, scale: 4 }),
    withholdingCertNumber: text('withholding_cert_number'),
    withholdingCertExpiry: date('withholding_cert_expiry'),
    withholdingCertR2Key: text('withholding_cert_r2_key'),
    defaultCategory: text('default_category'),
    defaultVatDeductible: boolean('default_vat_deductible').notNull().default(true),
    paymentTermsDays: integer('payment_terms_days').notNull().default(30),
    email: text('email'),
    phone: text('phone'),
    address: text('address'),
    notes: text('notes'),
    isArchived: boolean('is_archived').notNull().default(false),
    createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
    updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
  },
  (t) => ({
    tenantIdx: index('idx_vendors_tenant').on(t.tenantId, t.isArchived, t.name),
  }),
)

export type VendorRow = typeof vendors.$inferSelect
export type NewVendor = typeof vendors.$inferInsert
