-- Catalogo de tipos de operacion para facturacion

CREATE TABLE IF NOT EXISTS tipo_operacion (
    id TINYINT UNSIGNED NOT NULL PRIMARY KEY,
    codigo VARCHAR(20) NOT NULL,
    descripcion VARCHAR(120) NOT NULL,
    estado TINYINT(1) NOT NULL DEFAULT 1,
    created_at DATETIME NOT NULL,
    updated_at DATETIME NULL,
    deleted_at DATETIME NULL,
    UNIQUE KEY uq_tipo_operacion_codigo (codigo)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT IGNORE INTO tipo_operacion (id, codigo, descripcion, estado, created_at) VALUES
(1, 'VENTA', 'Venta', 1, NOW()),
(2, 'COMPRA', 'Compra', 1, NOW());

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

SET @tipo_operacion_col_exists := (
    SELECT COUNT(*)
    FROM information_schema.columns
    WHERE table_schema = DATABASE()
      AND table_name = 'facturacion_comprobantes'
      AND column_name = 'tipo_operacion_id'
);

SET @sql_tipo_operacion_col := IF(
    @facturacion_comprobantes_exists = 1 AND @tipo_operacion_col_exists = 0,
    'ALTER TABLE facturacion_comprobantes ADD COLUMN tipo_operacion_id TINYINT UNSIGNED NOT NULL DEFAULT 1 AFTER empresa_id',
    'SELECT 1'
);
PREPARE stmt_tipo_operacion_col FROM @sql_tipo_operacion_col;
EXECUTE stmt_tipo_operacion_col;
DEALLOCATE PREPARE stmt_tipo_operacion_col;

SET @sql_tipo_operacion_key := IF(
    @facturacion_comprobantes_exists = 1 AND @tipo_operacion_col_exists = 0,
    'ALTER TABLE facturacion_comprobantes ADD KEY idx_fact_comprobante_tipo_operacion (tipo_operacion_id)',
    'SELECT 1'
);
PREPARE stmt_tipo_operacion_key FROM @sql_tipo_operacion_key;
EXECUTE stmt_tipo_operacion_key;
DEALLOCATE PREPARE stmt_tipo_operacion_key;

SET @sql_tipo_operacion_fk := IF(
    @facturacion_comprobantes_exists = 1 AND @tipo_operacion_col_exists = 0,
    'ALTER TABLE facturacion_comprobantes ADD CONSTRAINT fk_fact_comprobante_tipo_operacion FOREIGN KEY (tipo_operacion_id) REFERENCES tipo_operacion(id)',
    'SELECT 1'
);
PREPARE stmt_tipo_operacion_fk FROM @sql_tipo_operacion_fk;
EXECUTE stmt_tipo_operacion_fk;
DEALLOCATE PREPARE stmt_tipo_operacion_fk;

SET @sql_tipo_operacion_update := IF(
    @facturacion_comprobantes_exists = 1,
    'UPDATE facturacion_comprobantes SET tipo_operacion_id = 1 WHERE tipo_operacion_id IS NULL OR tipo_operacion_id = 0',
    'SELECT 1'
);
PREPARE stmt_tipo_operacion_update FROM @sql_tipo_operacion_update;
EXECUTE stmt_tipo_operacion_update;
DEALLOCATE PREPARE stmt_tipo_operacion_update;
