import { initLogger } from "@/infrastructure/logger";
import rTracer from "cls-rtracer";
import { Sequelize } from "sequelize";

const logger = initLogger(rTracer);

const createCatalogTableIfNotExists = async (sequelize: Sequelize) => {
  try {
    // Consulta para verificar si la tabla existe
    const checkTableQuery = `
      SELECT COUNT(*) as count
      FROM information_schema.tables 
      WHERE table_schema = DATABASE() 
      AND table_name = 'catalog';`;

    const [result]: any = await sequelize.query(checkTableQuery);
    const tableExists = result.length > 0 && result[0].count > 0;

    if (!tableExists) {
      // Consulta para crear la tabla si no existe
      const createTableQuery = `
        CREATE TABLE catalog (
          id            char(36) COLLATE utf8mb4_bin NOT NULL,
          catalog_name  varchar(255) NOT NULL,
          id_article    bigint UNSIGNED NOT NULL,
          reference     varchar(255),
          points        bigint UNSIGNED DEFAULT 0,
          retail_price  bigint,
          created_at    datetime NOT NULL,
          updated_at    datetime NOT NULL,
          deleted_at    datetime,
          /* Keys */
          PRIMARY KEY (id)
        ) ENGINE = InnoDB
          COLLATE utf8mb4_unicode_ci;
        
        CREATE INDEX catalog_name_idx
          ON catalog (catalog_name);
        
        CREATE INDEX id_article_idx
          ON catalog (id_article);
        
        CREATE INDEX updated_at_idx
          ON catalog (updated_at);
      `;

      await sequelize.query(createTableQuery);
      logger.debug('Tabla "catalog" creada con éxito.');
    }
  } catch (error) {
    logger.error('Error al crear la tabla "catalog":', error);
  }
};

const createCatalogTranslationsTableIfNotExists = async (sequelize: Sequelize) => {
  try {
    // Consulta para verificar si la tabla existe
    const checkTableQuery = `
        SELECT COUNT(*) as count
        FROM information_schema.tables 
        WHERE table_schema = DATABASE() 
        AND table_name = 'catalog_translations';
      `;

    const [result]: any = await sequelize.query(checkTableQuery);
    const tableExists = result.length > 0 && result[0].count > 0;

    if (!tableExists) {
      // Consulta para crear la tabla si no existe
      const createTableQuery = `
          CREATE TABLE catalog_translations (
            id           varchar(255) NOT NULL,
            lang_code    varchar(2) NOT NULL DEFAULT 'es',
            description  varchar(255),
            catalog_id   char(36) COLLATE utf8mb4_bin,
            /* Keys */
            PRIMARY KEY (id),
            /* Foreign keys */
            CONSTRAINT catalog_translations_ibfk_1
                FOREIGN KEY (catalog_id)
                REFERENCES catalog(id)
                ON DELETE CASCADE
                ON UPDATE CASCADE
            ) ENGINE = InnoDB;

            CREATE INDEX catalog_id
            ON catalog_translations
            (catalog_id);

            CREATE INDEX lang_code_idx
            ON catalog_translations
            (lang_code);
        `;

      await sequelize.query(createTableQuery);
      logger.debug('Tabla "catalog_translations" creada con éxito.');
    }
  } catch (error) {
    logger.error('Error al crear la tabla "catalog_translations":', error);
  }
};

const createVCatalogViewIfNotExists = async (sequelize: Sequelize) => {
  try {
    // Consulta para verificar si la tabla existe
    const checkViewQuery = `
          SELECT COUNT(*) as count
          FROM information_schema.views 
          WHERE table_schema = DATABASE() 
          AND table_name = 'v_catalog';
        `;

    const [result]: any = await sequelize.query(checkViewQuery);
    const viewExists = result.length > 0 && result[0].count > 0;

    if (!viewExists) {
      // Consulta para crear la tabla si no existe
      const createViewQuery = `
            CREATE VIEW v_catalog AS
            SELECT 
            catalog.id AS id,
            catalog.catalog_name AS catalog_name,
            catalog.id_article AS id_article,
            catalog.reference AS reference,
            catalog.points AS points,
            catalog.retail_price AS retail_price,
            catalog.created_at AS created_at,
            catalog.updated_at AS updated_at,
            catalog_translations.lang_code AS lang_code,
            catalog_translations.description AS description
            FROM catalog
            JOIN catalog_translations ON catalog.id = catalog_translations.catalog_id
            WHERE catalog.deleted_at IS NULL;
        `;

      await sequelize.query(createViewQuery);
      logger.debug('Vista "v_catalog" creada con éxito.');
    }
  } catch (error) {
    logger.error('Error al crear la vista "v_catalog":', error);
  }
};

export const initStructure = async (sequelize) => {
  await createCatalogTableIfNotExists(sequelize);
  await createCatalogTranslationsTableIfNotExists(sequelize);
  await createVCatalogViewIfNotExists(sequelize);
};
