-- ============================================================
-- quoERP — Centros de Costo
-- Migracion: 028_cost_centers.sql
-- ============================================================
-- Agrega una dimension adicional a las lineas de asientos
-- contables para clasificar gastos e ingresos por departamento,
-- proyecto, area o cualquier agrupacion definida por la empresa.
-- ============================================================

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- Catalogo de centros de costo
CREATE TABLE IF NOT EXISTS cost_centers (
    id          INT UNSIGNED  NOT NULL AUTO_INCREMENT,
    company_id  INT UNSIGNED  NOT NULL,
    code        VARCHAR(20)   NOT NULL,
    name        VARCHAR(150)  NOT NULL,
    type        ENUM('department','project','area','other')
                NOT NULL DEFAULT 'department'
                COMMENT 'department=Departamento, project=Proyecto, area=Area, other=Otro',
    parent_id   INT UNSIGNED  DEFAULT NULL
                COMMENT 'Para jerarquia: CC hijo de otro CC',
    description VARCHAR(300)  DEFAULT NULL,
    is_active   TINYINT(1)    NOT NULL DEFAULT 1,
    sort_order  SMALLINT UNSIGNED NOT NULL DEFAULT 0,
    created_at  DATETIME      NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at  DATETIME      DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    UNIQUE KEY uk_code (company_id, code),
    INDEX idx_company  (company_id),
    INDEX idx_parent   (parent_id),
    INDEX idx_active   (is_active)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Agregar dimension de centro de costo a las lineas de asientos
ALTER TABLE journal_entry_lines
    ADD COLUMN IF NOT EXISTS cost_center_id INT UNSIGNED DEFAULT NULL
        COMMENT 'Centro de costo asignado a esta linea (opcional)';

SET FOREIGN_KEY_CHECKS = 1;

-- ─────────────────────────────────────────────────────────────
-- FIN DE MIGRACION
-- Tabla nueva: cost_centers
-- ALTER: journal_entry_lines (cost_center_id)
-- ─────────────────────────────────────────────────────────────
