-- ============================================================
-- quoERP — Modulo Activos Fijos (NIIF Ecuador)
-- Migracion: 022_fixed_assets.sql
-- Version: 1.0.0 | Fecha: 2026-06-07
-- ============================================================
-- Vidas utiles segun regulacion SRI / NIIF Ecuador:
--   Inmuebles (edificios): 20 anos (5% anual)
--   Maquinaria y Equipo:   10 anos (10% anual)
--   Vehiculos:              5 anos (20% anual)
--   Muebles y Enseres:     10 anos (10% anual)
--   Equipo de Computo:      3 anos (33.33% anual)
--   Equipo de Oficina:     10 anos (10% anual)
-- ============================================================

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ─────────────────────────────────────────────────────────────
-- TABLA: fixed_asset_categories — Categorias de activos fijos
-- ─────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS fixed_asset_categories (
    id                  INT UNSIGNED  NOT NULL AUTO_INCREMENT,
    company_id          INT UNSIGNED  DEFAULT NULL
        COMMENT 'NULL = categoria global del sistema',
    name                VARCHAR(120)  NOT NULL,
    useful_life_months  SMALLINT UNSIGNED NOT NULL DEFAULT 120
        COMMENT 'Vida util en meses (ej: 120 = 10 anos)',
    residual_pct        DECIMAL(5,2)  NOT NULL DEFAULT 10.00
        COMMENT 'Valor residual como porcentaje del costo de adquisicion',
    depreciation_method ENUM('straight_line') NOT NULL DEFAULT 'straight_line'
        COMMENT 'Metodo de depreciacion: straight_line = linea recta',
    -- Cuentas contables por defecto para esta categoria
    acc_asset           INT UNSIGNED  DEFAULT NULL COMMENT 'Cuenta del activo (1.2.xx)',
    acc_accum_dep       INT UNSIGNED  DEFAULT NULL COMMENT 'Depreciacion acumulada (1.2.xx contra-activo)',
    acc_dep_expense     INT UNSIGNED  DEFAULT NULL COMMENT 'Gasto depreciacion (5.3.xx)',
    is_active           TINYINT(1)    NOT NULL DEFAULT 1,
    sort_order          TINYINT UNSIGNED NOT NULL DEFAULT 0,
    created_at          DATETIME      NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    INDEX idx_company (company_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ─────────────────────────────────────────────────────────────
-- TABLA: fixed_assets — Activos fijos individuales
-- ─────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS fixed_assets (
    id                   INT UNSIGNED  NOT NULL AUTO_INCREMENT,
    company_id           INT UNSIGNED  NOT NULL,
    category_id          INT UNSIGNED  NOT NULL,
    code                 VARCHAR(30)   DEFAULT NULL COMMENT 'Codigo interno del activo',
    name                 VARCHAR(200)  NOT NULL,
    description          TEXT          DEFAULT NULL,
    -- Datos de adquisicion
    acquisition_date     DATE          NOT NULL,
    acquisition_cost     DECIMAL(14,4) NOT NULL DEFAULT 0
        COMMENT 'Costo historico de adquisicion',
    residual_value       DECIMAL(14,4) NOT NULL DEFAULT 0
        COMMENT 'Valor residual al fin de la vida util',
    -- Parametros de depreciacion
    useful_life_months   SMALLINT UNSIGNED NOT NULL DEFAULT 120,
    depreciation_method  ENUM('straight_line') NOT NULL DEFAULT 'straight_line',
    -- Depreciacion acumulada (actualizada en cada corrida)
    accumulated_depreciation DECIMAL(14,4) NOT NULL DEFAULT 0,
    -- Estado
    status               ENUM('active','fully_depreciated','disposed') NOT NULL DEFAULT 'active',
    -- Informacion adicional
    location             VARCHAR(150)  DEFAULT NULL,
    serial_number        VARCHAR(100)  DEFAULT NULL,
    provider_name        VARCHAR(150)  DEFAULT NULL,
    invoice_reference    VARCHAR(80)   DEFAULT NULL COMMENT 'Numero de factura de compra',
    -- Cuentas contables (sobreescriben las de la categoria si se especifican)
    acc_asset            INT UNSIGNED  DEFAULT NULL,
    acc_accum_dep        INT UNSIGNED  DEFAULT NULL,
    acc_dep_expense      INT UNSIGNED  DEFAULT NULL,
    -- Baja del activo
    disposal_date        DATE          DEFAULT NULL,
    disposal_value       DECIMAL(14,4) DEFAULT NULL COMMENT 'Valor de realizacion al dar de baja',
    disposal_reason      TEXT          DEFAULT NULL,
    disposal_entry_id    INT UNSIGNED  DEFAULT NULL,
    -- Trazabilidad
    acquisition_entry_id INT UNSIGNED  DEFAULT NULL COMMENT 'Asiento de compra/capitalizacion',
    created_by           INT UNSIGNED  DEFAULT NULL,
    created_at           DATETIME      NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at           DATETIME      DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    INDEX idx_company  (company_id),
    INDEX idx_category (category_id),
    INDEX idx_status   (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ─────────────────────────────────────────────────────────────
-- TABLA: fixed_asset_depreciation — Historial de depreciaciones
-- ─────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS fixed_asset_depreciation (
    id                   INT UNSIGNED  NOT NULL AUTO_INCREMENT,
    asset_id             INT UNSIGNED  NOT NULL,
    year                 SMALLINT UNSIGNED NOT NULL,
    month                TINYINT UNSIGNED  NOT NULL,
    period_label         VARCHAR(40)   NOT NULL,
    depreciation_amount  DECIMAL(14,4) NOT NULL DEFAULT 0,
    accumulated_before   DECIMAL(14,4) NOT NULL DEFAULT 0,
    accumulated_after    DECIMAL(14,4) NOT NULL DEFAULT 0,
    book_value_after     DECIMAL(14,4) NOT NULL DEFAULT 0,
    journal_entry_id     INT UNSIGNED  DEFAULT NULL,
    created_by           INT UNSIGNED  DEFAULT NULL,
    created_at           DATETIME      NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    UNIQUE KEY uk_asset_period (asset_id, year, month),
    INDEX idx_asset (asset_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ─────────────────────────────────────────────────────────────
-- Cuentas para ganancias/perdidas en baja de activos
-- ─────────────────────────────────────────────────────────────
ALTER TABLE company_account_map
    ADD COLUMN IF NOT EXISTS acc_asset_disposal_gain INT UNSIGNED DEFAULT NULL
        COMMENT 'Ganancia en baja de activos fijos (ingreso)',
    ADD COLUMN IF NOT EXISTS acc_asset_disposal_loss INT UNSIGNED DEFAULT NULL
        COMMENT 'Perdida en baja de activos fijos (gasto)';

-- ─────────────────────────────────────────────────────────────
-- SEED: Categorias globales de activos fijos (SRI Ecuador)
-- ─────────────────────────────────────────────────────────────
INSERT IGNORE INTO fixed_asset_categories (id, company_id, name, useful_life_months, residual_pct, sort_order) VALUES
(1, NULL, 'Inmuebles / Edificios',         240,  10.00, 10),
(2, NULL, 'Maquinaria y Equipo',           120,  10.00, 20),
(3, NULL, 'Vehiculos',                      60,  10.00, 30),
(4, NULL, 'Muebles y Enseres',             120,  10.00, 40),
(5, NULL, 'Equipo de Computo',              36,  10.00, 50),
(6, NULL, 'Equipo de Oficina',             120,  10.00, 60),
(7, NULL, 'Herramientas y Accesorios',      60,  10.00, 70),
(8, NULL, 'Terrenos',                        0,   0.00, 80);

SET FOREIGN_KEY_CHECKS = 1;

-- ─────────────────────────────────────────────────────────────
-- FIN DE MIGRACION
-- Tablas nuevas: fixed_asset_categories, fixed_assets, fixed_asset_depreciation
-- ALTER: company_account_map (acc_asset_disposal_gain/loss)
-- ─────────────────────────────────────────────────────────────
