// Test helpers and mock factories
// Note: jest is available globally in Jest test environment

// Mock repository factory
export function createMockRepository<T>() {
  return {
    find: jest.fn(),
    findOne: jest.fn(),
    findAndCount: jest.fn(),
    create: jest.fn((data: Partial<T>) => data as T),
    save: jest.fn((entity: T) => Promise.resolve(entity)),
    update: jest.fn(),
    delete: jest.fn(),
    remove: jest.fn((entity: T) => Promise.resolve(entity)),
    softDelete: jest.fn(),
    createQueryBuilder: jest.fn(() => createMockQueryBuilder()),
    count: jest.fn(),
    merge: jest.fn((entity: T, ...sources: Partial<T>[]) => Object.assign(entity as object, ...sources)),
  };
}

// Mock query builder
export function createMockQueryBuilder() {
  const qb = {
    where: jest.fn().mockReturnThis(),
    andWhere: jest.fn().mockReturnThis(),
    orWhere: jest.fn().mockReturnThis(),
    leftJoin: jest.fn().mockReturnThis(),
    leftJoinAndSelect: jest.fn().mockReturnThis(),
    innerJoin: jest.fn().mockReturnThis(),
    innerJoinAndSelect: jest.fn().mockReturnThis(),
    select: jest.fn().mockReturnThis(),
    addSelect: jest.fn().mockReturnThis(),
    orderBy: jest.fn().mockReturnThis(),
    addOrderBy: jest.fn().mockReturnThis(),
    skip: jest.fn().mockReturnThis(),
    take: jest.fn().mockReturnThis(),
    getOne: jest.fn(),
    getMany: jest.fn(),
    getManyAndCount: jest.fn(),
    getCount: jest.fn(),
    execute: jest.fn(),
    setParameter: jest.fn().mockReturnThis(),
    setParameters: jest.fn().mockReturnThis(),
  };
  return qb;
}

// Partner factory
export function createMockPartner(overrides = {}) {
  return {
    id: 'partner-uuid-1',
    tenantId: global.testTenantId,
    name: 'Test Partner',
    email: 'partner@test.com',
    phone: '+1234567890',
    isCustomer: true,
    isSupplier: false,
    isActive: true,
    creditLimit: 10000,
    currentBalance: 0,
    createdAt: new Date(),
    updatedAt: new Date(),
    deletedAt: null,
    ...overrides,
  };
}

// Product factory
export function createMockProduct(overrides = {}) {
  return {
    id: 'product-uuid-1',
    tenantId: global.testTenantId,
    sku: 'PROD-001',
    name: 'Test Product',
    description: 'Test product description',
    productType: 'product',
    salePrice: 100,
    costPrice: 50,
    currency: 'MXN',
    taxRate: 16,
    isActive: true,
    isSellable: true,
    isPurchasable: true,
    createdAt: new Date(),
    updatedAt: new Date(),
    deletedAt: null,
    ...overrides,
  };
}

// Warehouse factory
export function createMockWarehouse(overrides = {}) {
  return {
    id: 'warehouse-uuid-1',
    tenantId: global.testTenantId,
    code: 'WH-001',
    name: 'Test Warehouse',
    address: '123 Test St',
    city: 'Test City',
    state: 'Test State',
    country: 'MEX',
    isActive: true,
    isDefault: true,
    createdAt: new Date(),
    updatedAt: new Date(),
    deletedAt: null,
    ...overrides,
  };
}

// Invoice factory
export function createMockInvoice(overrides = {}) {
  return {
    id: 'invoice-uuid-1',
    tenantId: global.testTenantId,
    invoiceNumber: 'INV-001',
    invoiceType: 'sale',
    partnerId: 'partner-uuid-1',
    status: 'draft',
    subtotal: 1000,
    taxAmount: 160,
    total: 1160,
    currency: 'MXN',
    invoiceDate: new Date(),
    dueDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
    createdAt: new Date(),
    updatedAt: new Date(),
    deletedAt: null,
    ...overrides,
  };
}

// Employee factory
export function createMockEmployee(overrides = {}) {
  return {
    id: 'employee-uuid-1',
    tenantId: global.testTenantId,
    employeeNumber: 'EMP-001',
    firstName: 'John',
    lastName: 'Doe',
    email: 'john.doe@test.com',
    departmentId: 'dept-uuid-1',
    position: 'Developer',
    hireDate: new Date(),
    isActive: true,
    createdAt: new Date(),
    updatedAt: new Date(),
    deletedAt: null,
    ...overrides,
  };
}

// Account factory
export function createMockAccount(overrides = {}) {
  return {
    id: 'account-uuid-1',
    tenantId: global.testTenantId,
    code: '1000',
    name: 'Cash',
    accountType: 'asset',
    isActive: true,
    balance: 0,
    createdAt: new Date(),
    updatedAt: new Date(),
    deletedAt: null,
    ...overrides,
  };
}

// Quotation factory
export function createMockQuotation(overrides: Record<string, any> = {}) {
  return {
    id: 'quotation-uuid-1',
    tenant_id: global.testTenantId,
    company_id: 'company-uuid-1',
    company_name: 'Test Company',
    name: 'QUO-000001',
    partner_id: 'partner-uuid-1',
    partner_name: 'Test Partner',
    quotation_date: new Date(),
    validity_date: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
    currency_id: 'currency-uuid-1',
    currency_code: 'MXN',
    pricelist_id: null,
    user_id: 'user-uuid-1',
    sales_team_id: null,
    amount_untaxed: 1000,
    amount_tax: 160,
    amount_total: 1160,
    status: 'draft' as const,
    sale_order_id: null,
    notes: null,
    terms_conditions: null,
    lines: [],
    created_at: new Date(),
    ...overrides,
  };
}

// Quotation line factory
export function createMockQuotationLine(overrides: Record<string, any> = {}) {
  return {
    id: 'quotation-line-uuid-1',
    quotation_id: 'quotation-uuid-1',
    product_id: 'product-uuid-1',
    product_name: 'Test Product',
    description: 'Test product description',
    quantity: 10,
    uom_id: 'uom-uuid-1',
    uom_name: 'Unit',
    price_unit: 100,
    discount: 0,
    tax_ids: [],
    amount_untaxed: 1000,
    amount_tax: 160,
    amount_total: 1160,
    ...overrides,
  };
}

// Sales Order factory
export function createMockSalesOrder(overrides: Record<string, any> = {}) {
  return {
    id: 'order-uuid-1',
    tenant_id: global.testTenantId,
    company_id: 'company-uuid-1',
    company_name: 'Test Company',
    name: 'SO-000001',
    client_order_ref: null,
    partner_id: 'partner-uuid-1',
    partner_name: 'Test Partner',
    order_date: new Date(),
    validity_date: null,
    commitment_date: null,
    currency_id: 'currency-uuid-1',
    currency_code: 'MXN',
    pricelist_id: null,
    payment_term_id: null,
    user_id: 'user-uuid-1',
    sales_team_id: null,
    amount_untaxed: 1000,
    amount_tax: 160,
    amount_total: 1160,
    status: 'draft' as const,
    invoice_status: 'pending' as const,
    delivery_status: 'pending' as const,
    invoice_policy: 'order' as const,
    picking_id: null,
    notes: null,
    terms_conditions: null,
    lines: [],
    created_at: new Date(),
    confirmed_at: null,
    ...overrides,
  };
}

// Sales Order line factory
export function createMockSalesOrderLine(overrides: Record<string, any> = {}) {
  return {
    id: 'order-line-uuid-1',
    order_id: 'order-uuid-1',
    product_id: 'product-uuid-1',
    product_name: 'Test Product',
    description: 'Test product description',
    quantity: 10,
    qty_delivered: 0,
    qty_invoiced: 0,
    uom_id: 'uom-uuid-1',
    uom_name: 'Unit',
    price_unit: 100,
    discount: 0,
    tax_ids: [],
    amount_untaxed: 1000,
    amount_tax: 160,
    amount_total: 1160,
    analytic_account_id: null,
    ...overrides,
  };
}

// Purchase Order factory
export function createMockPurchaseOrder(overrides: Record<string, any> = {}) {
  return {
    id: 'purchase-order-uuid-1',
    tenant_id: global.testTenantId,
    company_id: 'company-uuid-1',
    company_name: 'Test Company',
    name: 'PO-000001',
    ref: null,
    partner_id: 'partner-uuid-1',
    partner_name: 'Test Supplier',
    order_date: new Date(),
    expected_date: null,
    effective_date: null,
    currency_id: 'currency-uuid-1',
    currency_code: 'MXN',
    payment_term_id: null,
    amount_untaxed: 1000,
    amount_tax: 160,
    amount_total: 1160,
    status: 'draft' as const,
    receipt_status: 'pending',
    invoice_status: 'pending',
    notes: null,
    lines: [],
    created_at: new Date(),
    confirmed_at: null,
    ...overrides,
  };
}

// Purchase Order line factory
export function createMockPurchaseOrderLine(overrides: Record<string, any> = {}) {
  return {
    id: 'purchase-line-uuid-1',
    product_id: 'product-uuid-1',
    product_name: 'Test Product',
    product_code: 'PROD-001',
    description: 'Test product description',
    quantity: 10,
    qty_received: 0,
    qty_invoiced: 0,
    uom_id: 'uom-uuid-1',
    uom_name: 'Unit',
    price_unit: 100,
    discount: 0,
    amount_untaxed: 1000,
    amount_tax: 160,
    amount_total: 1160,
    expected_date: null,
    ...overrides,
  };
}

// RFQ factory
export function createMockRfq(overrides: Record<string, any> = {}) {
  return {
    id: 'rfq-uuid-1',
    tenant_id: global.testTenantId,
    company_id: 'company-uuid-1',
    company_name: 'Test Company',
    name: 'RFQ-000001',
    partner_ids: ['supplier-uuid-1'],
    partner_names: ['Test Supplier'],
    request_date: new Date(),
    deadline_date: null,
    response_date: null,
    status: 'draft' as const,
    description: null,
    notes: null,
    lines: [],
    created_at: new Date(),
    ...overrides,
  };
}

// RFQ line factory
export function createMockRfqLine(overrides: Record<string, any> = {}) {
  return {
    id: 'rfq-line-uuid-1',
    rfq_id: 'rfq-uuid-1',
    product_id: 'product-uuid-1',
    product_name: 'Test Product',
    product_code: 'PROD-001',
    description: 'Test product description',
    quantity: 10,
    uom_id: 'uom-uuid-1',
    uom_name: 'Unit',
    created_at: new Date(),
    ...overrides,
  };
}

// Lead factory
export function createMockLead(overrides: Record<string, any> = {}) {
  return {
    id: 'lead-uuid-1',
    tenant_id: global.testTenantId,
    company_id: 'company-uuid-1',
    company_name: 'Test Company',
    name: 'Test Lead',
    ref: null,
    contact_name: 'John Doe',
    email: 'john@test.com',
    phone: '+1234567890',
    mobile: null,
    website: null,
    company_prospect_name: 'Prospect Inc',
    job_position: 'Manager',
    industry: 'Technology',
    stage_id: 'stage-uuid-1',
    stage_name: 'New',
    status: 'new' as const,
    user_id: 'user-uuid-1',
    sales_team_id: null,
    source: 'website' as const,
    priority: 1,
    probability: 10,
    expected_revenue: 5000,
    date_open: new Date(),
    date_closed: null,
    partner_id: null,
    opportunity_id: null,
    lost_reason_id: null,
    description: null,
    notes: null,
    tags: [],
    created_at: new Date(),
    ...overrides,
  };
}

// Opportunity factory
export function createMockOpportunity(overrides: Record<string, any> = {}) {
  return {
    id: 'opportunity-uuid-1',
    tenant_id: global.testTenantId,
    company_id: 'company-uuid-1',
    company_name: 'Test Company',
    name: 'Test Opportunity',
    ref: null,
    partner_id: 'partner-uuid-1',
    partner_name: 'Test Partner',
    contact_name: 'John Doe',
    email: 'john@test.com',
    phone: '+1234567890',
    stage_id: 'stage-uuid-1',
    stage_name: 'Qualification',
    status: 'open' as const,
    user_id: 'user-uuid-1',
    sales_team_id: null,
    priority: 2,
    probability: 30,
    expected_revenue: 10000,
    recurring_revenue: null,
    recurring_plan: null,
    date_deadline: null,
    date_closed: null,
    date_last_activity: null,
    lead_id: null,
    source: 'website' as const,
    lost_reason_id: null,
    quotation_id: null,
    order_id: null,
    description: null,
    notes: null,
    tags: [],
    created_at: new Date(),
    ...overrides,
  };
}

// Stage factory (for both Lead and Opportunity stages)
export function createMockStage(overrides: Record<string, any> = {}) {
  return {
    id: 'stage-uuid-1',
    tenant_id: global.testTenantId,
    name: 'New',
    sequence: 1,
    is_won: false,
    probability: 10,
    requirements: null,
    active: true,
    created_at: new Date(),
    ...overrides,
  };
}

// Lost Reason factory
export function createMockLostReason(overrides: Record<string, any> = {}) {
  return {
    id: 'lost-reason-uuid-1',
    tenant_id: global.testTenantId,
    name: 'Too expensive',
    description: 'Customer found a cheaper alternative',
    active: true,
    created_at: new Date(),
    ...overrides,
  };
}

// Project factory
export function createMockProject(overrides: Record<string, any> = {}) {
  return {
    id: 'project-uuid-1',
    tenant_id: global.testTenantId,
    company_id: 'company-uuid-1',
    company_name: 'Test Company',
    name: 'Test Project',
    code: 'PROJ-001',
    description: 'Test project description',
    manager_id: 'user-uuid-1',
    manager_name: 'John Manager',
    partner_id: 'partner-uuid-1',
    partner_name: 'Test Partner',
    analytic_account_id: null,
    date_start: new Date(),
    date_end: null,
    status: 'active' as const,
    privacy: 'public' as const,
    allow_timesheets: true,
    color: '#3498db',
    task_count: 5,
    completed_task_count: 2,
    created_at: new Date(),
    ...overrides,
  };
}

// Task factory
export function createMockTask(overrides: Record<string, any> = {}) {
  return {
    id: 'task-uuid-1',
    tenant_id: global.testTenantId,
    project_id: 'project-uuid-1',
    project_name: 'Test Project',
    stage_id: 'stage-uuid-1',
    stage_name: 'To Do',
    name: 'Test Task',
    description: 'Test task description',
    assigned_to: 'user-uuid-1',
    assigned_name: 'John Doe',
    parent_id: null,
    parent_name: null,
    date_deadline: null,
    estimated_hours: 8,
    spent_hours: 0,
    priority: 'normal' as const,
    status: 'todo' as const,
    sequence: 1,
    color: null,
    created_at: new Date(),
    ...overrides,
  };
}

// Timesheet factory
export function createMockTimesheet(overrides: Record<string, any> = {}) {
  return {
    id: 'timesheet-uuid-1',
    tenant_id: global.testTenantId,
    project_id: 'project-uuid-1',
    project_name: 'Test Project',
    task_id: 'task-uuid-1',
    task_name: 'Test Task',
    employee_id: 'employee-uuid-1',
    employee_name: 'John Doe',
    date: new Date(),
    hours: 4,
    description: 'Worked on feature X',
    billable: true,
    invoiced: false,
    created_at: new Date(),
    ...overrides,
  };
}

// Activity factory (CRM)
export function createMockActivity(overrides: Record<string, any> = {}) {
  return {
    id: 'activity-uuid-1',
    tenant_id: global.testTenantId,
    company_id: 'company-uuid-1',
    company_name: 'Test Company',
    activity_type: 'call' as const,
    name: 'Test Activity',
    description: null,
    user_id: 'user-uuid-1',
    user_name: 'John Doe',
    res_model: 'opportunity',
    res_id: 'opportunity-uuid-1',
    res_name: 'Test Opportunity',
    partner_id: 'partner-uuid-1',
    partner_name: 'Test Partner',
    scheduled_date: new Date(),
    date_done: null,
    duration_hours: 1,
    status: 'scheduled' as const,
    priority: 1,
    notes: null,
    created_at: new Date(),
    created_by: 'user-uuid-1',
    ...overrides,
  };
}

// =====================================================
// Core Catalog Factories
// =====================================================

// Country factory
export function createMockCountry(overrides: Record<string, any> = {}) {
  return {
    id: 'country-uuid-1',
    code: 'MX',
    codeAlpha3: 'MEX',
    name: 'México',
    phoneCode: '+52',
    currencyCode: 'MXN',
    createdAt: new Date(),
    ...overrides,
  };
}

// State factory
export function createMockState(overrides: Record<string, any> = {}) {
  return {
    id: 'state-uuid-1',
    countryId: 'country-uuid-1',
    code: 'JAL',
    name: 'Jalisco',
    timezone: 'America/Mexico_City',
    isActive: true,
    createdAt: new Date(),
    updatedAt: new Date(),
    ...overrides,
  };
}

// Currency factory (core)
export function createMockCurrency(overrides: Record<string, any> = {}) {
  return {
    id: 'currency-uuid-1',
    code: 'MXN',
    name: 'Peso Mexicano',
    symbol: '$',
    decimals: 2,
    rounding: 0.01,
    active: true,
    createdAt: new Date(),
    ...overrides,
  };
}

// Currency Rate factory
export function createMockCurrencyRate(overrides: Record<string, any> = {}) {
  return {
    id: 'rate-uuid-1',
    tenantId: global.testTenantId,
    fromCurrencyId: 'currency-uuid-usd',
    toCurrencyId: 'currency-uuid-mxn',
    rate: 17.50,
    rateDate: new Date(),
    source: 'manual' as const,
    createdBy: global.testUserId,
    createdAt: new Date(),
    ...overrides,
  };
}

// UoM Category factory
export function createMockUomCategory(overrides: Record<string, any> = {}) {
  return {
    id: 'uom-category-uuid-1',
    tenantId: null,
    name: 'Unidades',
    description: 'Unidades discretas',
    createdAt: new Date(),
    updatedAt: new Date(),
    ...overrides,
  };
}

// UoM factory
export function createMockUom(overrides: Record<string, any> = {}) {
  return {
    id: 'uom-uuid-1',
    tenantId: null,
    categoryId: 'uom-category-uuid-1',
    code: 'unit',
    name: 'Unidad',
    symbol: 'u',
    uomType: 'reference' as const,
    factor: 1.0,
    rounding: 0.01,
    isActive: true,
    createdAt: new Date(),
    updatedAt: new Date(),
    ...overrides,
  };
}

// Payment Term factory
export function createMockPaymentTerm(overrides: Record<string, any> = {}) {
  return {
    id: 'payment-term-uuid-1',
    tenantId: global.testTenantId,
    code: 'NET30',
    name: 'Neto 30 días',
    description: 'Pago en 30 días',
    dueDays: 30,
    discountPercent: null,
    discountDays: null,
    isImmediate: false,
    isActive: true,
    lines: [],
    createdAt: new Date(),
    updatedAt: new Date(),
    ...overrides,
  };
}

// Discount Rule factory
export function createMockDiscountRule(overrides: Record<string, any> = {}) {
  return {
    id: 'discount-rule-uuid-1',
    tenantId: global.testTenantId,
    code: 'PROMO10',
    name: '10% de descuento',
    description: 'Promoción del 10%',
    discountType: 'percentage' as const,
    discountValue: 10,
    maxDiscountAmount: null,
    appliesTo: 'all' as const,
    appliesToId: null,
    conditionType: 'none' as const,
    conditionValue: null,
    startDate: null,
    endDate: null,
    priority: 1,
    combinable: true,
    usageLimit: null,
    usageCount: 0,
    isActive: true,
    createdAt: new Date(),
    updatedAt: new Date(),
    ...overrides,
  };
}

// Product Category factory (core)
export function createMockProductCategory(overrides: Record<string, any> = {}) {
  return {
    id: 'product-category-uuid-1',
    tenantId: global.testTenantId,
    parentId: null,
    code: 'GEN',
    name: 'General',
    description: 'Categoría general',
    hierarchyPath: '/GEN',
    hierarchyLevel: 1,
    isActive: true,
    createdAt: new Date(),
    updatedAt: new Date(),
    ...overrides,
  };
}

// Sequence factory
export function createMockSequence(overrides: Record<string, any> = {}) {
  return {
    id: 'sequence-uuid-1',
    tenantId: global.testTenantId,
    code: 'invoice',
    name: 'Facturas',
    prefix: 'INV-',
    suffix: null,
    padding: 6,
    step: 1,
    currentNumber: 1,
    resetFrequency: null,
    lastResetDate: null,
    isActive: true,
    createdAt: new Date(),
    updatedAt: new Date(),
    ...overrides,
  };
}
