import { DataSource } from 'typeorm';
import { config } from './index.js';

// Import Core Entities
import {
  Tenant,
  User,
  Currency,
  CurrencyRate,
  Country,
  State,
  UomCategory,
  Uom,
  ProductCategory,
  Sequence,
  PaymentTerm,
  DiscountRule,
} from '../modules/core/entities/index.js';

// Import Auth Entities
import {
  Permission,
  Role,
} from '../modules/auth/entities/index.js';

// Import Inventory Entities (if they exist)
import {
  Product,
  Location,
  Lot,
  StockQuant,
  StockMove,
  StockLevel,
  StockMovement,
  InventoryCount,
  InventoryCountLine,
  InventoryAdjustment,
  InventoryAdjustmentLine,
  TransferOrder,
  TransferOrderLine,
  StockValuationLayer,
  Picking,
} from '../modules/inventory/entities/index.js';

// Import Partner Entities
import { Partner } from '../modules/partners/entities/index.js';

// Import Sales Entities
import {
  SalesOrder,
  SalesOrderItem,
  Quotation,
  QuotationItem,
} from '../modules/sales/entities/index.js';

// Simple logger
const logger = {
  info: (msg: string, meta?: object) => console.info(`[INFO] ${msg}`, JSON.stringify(meta || {})),
  warn: (msg: string, meta?: object) => console.warn(`[WARN] ${msg}`, JSON.stringify(meta || {})),
  error: (msg: string, meta?: object) => console.error(`[ERROR] ${msg}`, JSON.stringify(meta || {})),
};

/**
 * TypeORM DataSource configuration for erp-construccion
 */
export const AppDataSource = new DataSource({
  type: 'postgres',
  host: config.database.host,
  port: config.database.port,
  username: config.database.user,
  password: config.database.password,
  database: config.database.name,

  // Schema por defecto
  schema: 'public',

  // Entities registradas
  entities: [
    // Core Entities
    Tenant,
    User,
    Currency,
    CurrencyRate,
    Country,
    State,
    UomCategory,
    Uom,
    ProductCategory,
    Sequence,
    PaymentTerm,
    DiscountRule,
    // Auth Entities
    Permission,
    Role,
    // Partner Entities
    Partner,
    // Inventory Entities
    Product,
    Location,
    Lot,
    StockQuant,
    StockMove,
    StockLevel,
    StockMovement,
    InventoryCount,
    InventoryCountLine,
    InventoryAdjustment,
    InventoryAdjustmentLine,
    TransferOrder,
    TransferOrderLine,
    StockValuationLayer,
    Picking,
    // Sales Entities
    SalesOrder,
    SalesOrderItem,
    Quotation,
    QuotationItem,
  ],

  // NO usar synchronize en producción - usamos DDL manual
  synchronize: false,

  // Logging
  logging: config.env === 'development' ? ['query', 'error', 'warn'] : ['error'],

  // Log queries lentas (> 1000ms)
  maxQueryExecutionTime: 1000,

  // Pool de conexiones
  extra: {
    max: 10,
    min: 2,
    idleTimeoutMillis: 30000,
    connectionTimeoutMillis: 2000,
  },

  cache: false,
});

/**
 * Inicializa la conexión TypeORM
 */
export async function initializeTypeORM(): Promise<boolean> {
  try {
    if (!AppDataSource.isInitialized) {
      await AppDataSource.initialize();
      logger.info('TypeORM DataSource initialized successfully', {
        database: config.database.name,
        host: config.database.host,
      });
      return true;
    }
    logger.warn('TypeORM DataSource already initialized');
    return true;
  } catch (error) {
    logger.error('Failed to initialize TypeORM DataSource', {
      error: (error as Error).message,
    });
    return false;
  }
}

/**
 * Cierra la conexión TypeORM
 */
export async function closeTypeORM(): Promise<void> {
  try {
    if (AppDataSource.isInitialized) {
      await AppDataSource.destroy();
      logger.info('TypeORM DataSource closed');
    }
  } catch (error) {
    logger.error('Error closing TypeORM DataSource', {
      error: (error as Error).message,
    });
  }
}

/**
 * Obtiene el estado de la conexión TypeORM
 */
export function isTypeORMConnected(): boolean {
  return AppDataSource.isInitialized;
}
