-- Codigos estandar para catalogo de productos/servicios

SET @catalogo_items_exists := (
    SELECT COUNT(*)
    FROM information_schema.tables
    WHERE table_schema = DATABASE()
      AND table_name = 'catalogo_items'
);

SET @sql_catalogo_items := IF(
    @catalogo_items_exists = 0,
    'SELECT 1',
    'SELECT 1'
);
PREPARE stmt_catalogo_items FROM @sql_catalogo_items;
EXECUTE stmt_catalogo_items;
DEALLOCATE PREPARE stmt_catalogo_items;

SET @codigo_sunat_exists := (
    SELECT COUNT(*)
    FROM information_schema.columns
    WHERE table_schema = DATABASE()
      AND table_name = 'catalogo_items'
      AND column_name = 'codigo_sunat'
);

SET @sql_codigo_sunat := IF(
    @catalogo_items_exists = 1 AND @codigo_sunat_exists = 0,
    'ALTER TABLE catalogo_items ADD COLUMN codigo_sunat VARCHAR(20) NULL AFTER codigo',
    'SELECT 1'
);
PREPARE stmt_codigo_sunat FROM @sql_codigo_sunat;
EXECUTE stmt_codigo_sunat;
DEALLOCATE PREPARE stmt_codigo_sunat;

SET @codigo_gs1_exists := (
    SELECT COUNT(*)
    FROM information_schema.columns
    WHERE table_schema = DATABASE()
      AND table_name = 'catalogo_items'
      AND column_name = 'codigo_gs1'
);

SET @sql_codigo_gs1 := IF(
    @catalogo_items_exists = 1 AND @codigo_gs1_exists = 0,
    'ALTER TABLE catalogo_items ADD COLUMN codigo_gs1 VARCHAR(20) NULL AFTER codigo_sunat',
    'SELECT 1'
);
PREPARE stmt_codigo_gs1 FROM @sql_codigo_gs1;
EXECUTE stmt_codigo_gs1;
DEALLOCATE PREPARE stmt_codigo_gs1;
