-- =============================================================================
-- Переход: counterparties → v_contractors (1С)
-- manufacturer_counterparty_map: counterparty_id → contractor_1c_id
-- Контрагенты и производители из 1С (v_contractors, v_producers)
-- =============================================================================

USE [mag_pbi]
GO

SET NOCOUNT ON;

-- Удаляем представления, ссылающиеся на map/counterparties
IF OBJECT_ID(N'[analytics].[v_manufacturer_counterparty_mapping]', N'V') IS NOT NULL
    DROP VIEW [analytics].[v_manufacturer_counterparty_mapping];
GO

-- Удалить FK manufacturer_counterparty_map → counterparties (если есть)
DECLARE @fk NVARCHAR(256);
SELECT @fk = name FROM sys.foreign_keys 
WHERE parent_object_id = OBJECT_ID(N'[analytics].[manufacturer_counterparty_map]')
  AND referenced_object_id = OBJECT_ID(N'[analytics].[counterparties]');
IF @fk IS NOT NULL
    EXEC('ALTER TABLE [analytics].[manufacturer_counterparty_map] DROP CONSTRAINT ' + @fk);
GO

-- Очистить таблицу привязки
TRUNCATE TABLE [analytics].[manufacturer_counterparty_map];
PRINT 'manufacturer_counterparty_map: очищена';
GO

-- Заменить counterparty_id на contractor_1c_id
IF EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID(N'[analytics].[manufacturer_counterparty_map]') AND name = 'counterparty_id')
BEGIN
    ALTER TABLE [analytics].[manufacturer_counterparty_map] DROP COLUMN [counterparty_id];
    PRINT 'Удалена колонка counterparty_id';
END
IF NOT EXISTS (SELECT 1 FROM sys.columns WHERE object_id = OBJECT_ID(N'[analytics].[manufacturer_counterparty_map]') AND name = 'contractor_1c_id')
BEGIN
    ALTER TABLE [analytics].[manufacturer_counterparty_map] ADD [contractor_1c_id] BINARY(16) NOT NULL;
    PRINT 'Добавлена колонка contractor_1c_id';
END
GO

-- Удалить старые уникальные ограничения (на counterparty_id), создать новое
DECLARE @uq NVARCHAR(256);
SELECT @uq = name FROM sys.key_constraints 
WHERE parent_object_id = OBJECT_ID(N'[analytics].[manufacturer_counterparty_map]')
  AND type = 'UQ' AND name = 'UQ_mcm_counterparty';
IF @uq IS NOT NULL
    EXEC('ALTER TABLE [analytics].[manufacturer_counterparty_map] DROP CONSTRAINT ' + @uq);

SELECT @uq = name FROM sys.key_constraints 
WHERE parent_object_id = OBJECT_ID(N'[analytics].[manufacturer_counterparty_map]')
  AND type = 'UQ' AND name = 'UQ_mcm_pair';
IF @uq IS NOT NULL
    EXEC('ALTER TABLE [analytics].[manufacturer_counterparty_map] DROP CONSTRAINT ' + @uq);

-- Один контрагент — один производитель
IF NOT EXISTS (SELECT 1 FROM sys.key_constraints 
               WHERE parent_object_id = OBJECT_ID(N'[analytics].[manufacturer_counterparty_map]') AND name = 'UQ_mcm_contractor')
    ALTER TABLE [analytics].[manufacturer_counterparty_map] ADD CONSTRAINT [UQ_mcm_contractor] UNIQUE ([contractor_1c_id]);
-- Уникальная пара
IF NOT EXISTS (SELECT 1 FROM sys.key_constraints 
               WHERE parent_object_id = OBJECT_ID(N'[analytics].[manufacturer_counterparty_map]') AND name = 'UQ_mcm_pair')
    ALTER TABLE [analytics].[manufacturer_counterparty_map] ADD CONSTRAINT [UQ_mcm_pair] UNIQUE ([manufacturer_id], [contractor_1c_id]);
GO

-- Удалить таблицу counterparties
IF OBJECT_ID(N'[analytics].[counterparties]', N'U') IS NOT NULL
BEGIN
    DROP TABLE [analytics].[counterparties];
    PRINT 'Удалена таблица analytics.counterparties';
END
GO

-- Создать v_contractors, v_producers если не существуют
IF OBJECT_ID(N'[analytics].[v_contractors]', N'V') IS NULL
BEGIN
    EXEC('
    CREATE VIEW [analytics].[v_contractors] AS
    SELECT
        c._IDRRef AS contractor_1c_id,
        LOWER(CONCAT(
            SUBSTRING(CONVERT(nvarchar(36), c._IDRRef, 2), 25, 8), ''-'',
            SUBSTRING(CONVERT(nvarchar(36), c._IDRRef, 2), 21, 4), ''-'',
            SUBSTRING(CONVERT(nvarchar(36), c._IDRRef, 2), 17, 4), ''-'',
            SUBSTRING(CONVERT(nvarchar(36), c._IDRRef, 2), 1, 4), ''-'',
            SUBSTRING(CONVERT(nvarchar(36), c._IDRRef, 2), 5, 12)
        )) AS contractor_id,
        c._Description AS contractor_name
    FROM [MAG_2019].[dbo].[_Reference168] c
    WHERE c._Marked = 0');
    PRINT 'Создано представление v_contractors';
END

IF OBJECT_ID(N'[analytics].[v_producers]', N'V') IS NULL
BEGIN
    EXEC('
    CREATE VIEW [analytics].[v_producers] AS
    SELECT
        pr._IDRRef AS producer_1c_id,
        LOWER(CONCAT(
            SUBSTRING(CONVERT(nvarchar(36), pr._IDRRef, 2), 25, 8), ''-'',
            SUBSTRING(CONVERT(nvarchar(36), pr._IDRRef, 2), 21, 4), ''-'',
            SUBSTRING(CONVERT(nvarchar(36), pr._IDRRef, 2), 17, 4), ''-'',
            SUBSTRING(CONVERT(nvarchar(36), pr._IDRRef, 2), 1, 4), ''-'',
            SUBSTRING(CONVERT(nvarchar(36), pr._IDRRef, 2), 5, 12)
        )) AS producer_id,
        pr._Description AS producer_name
    FROM [MAG_2019].[dbo].[_Reference260] pr
    WHERE pr._Marked = 0');
    PRINT 'Создано представление v_producers';
END
GO

-- Представление для API: map + manufacturer + contractor/producer (из 1С)
CREATE VIEW [analytics].[v_manufacturer_counterparty_mapping] AS
SELECT
    mcm.id,
    mcm.manufacturer_id,
    p.producer_id,
    man.manufacturer AS manufacturer_name,
    mcm.contractor_1c_id,
    c.contractor_id,
    c.contractor_name AS contractor_name,
    man.days_of_sales,
    man.logistics_days,
    man.roic_norm
FROM [analytics].[manufacturer_counterparty_map] mcm
LEFT JOIN [analytics].[manufacturers] man ON man.id = mcm.manufacturer_id
LEFT JOIN [analytics].[v_contractors] c ON c.contractor_1c_id = mcm.contractor_1c_id
LEFT JOIN [analytics].[v_producers] p ON LTRIM(RTRIM(p.producer_name)) = LTRIM(RTRIM(man.manufacturer));
GO

-- Исправить [analytics].[get_orders_list]: counterparties удалена, map по contractor_1c_id,
-- manufacturers без ROI_norm/n_percent/n_days/m_percent/m_days — использовать v_manufacturers_roi_compat
IF OBJECT_ID(N'[analytics].[get_orders_list]', N'V') IS NOT NULL
BEGIN
    DECLARE @def NVARCHAR(MAX);
    SELECT @def = OBJECT_DEFINITION(OBJECT_ID(N'[analytics].[get_orders_list]'));
    IF @def LIKE N'%counterparties%'
    BEGIN
        SET @def = REPLACE(@def, N'LEFT JOIN [analytics].[counterparties] cp ON cp.[counterparty] = r._Description', N'');
        SET @def = REPLACE(@def, N'map.[counterparty_id] = cp.id', N'map.[contractor_1c_id] = r._IDRRef');
        -- manufacturers без старых полей — join на v_manufacturers_roi_compat (ROI_norm, n_percent, n_days, m_percent, m_days)
        IF @def LIKE N'%ROI_norm%' AND OBJECT_ID(N'[analytics].[v_manufacturers_roi_compat]', N'V') IS NOT NULL
            SET @def = REPLACE(@def, N'[analytics].[manufacturers] man', N'[analytics].[v_manufacturers_roi_compat] man');
        DROP VIEW [analytics].[get_orders_list];
        EXEC sp_executesql @def;
        PRINT 'Обновлено представление analytics.get_orders_list';
    END
END
GO

PRINT 'Готово: manufacturer_counterparty_map с contractor_1c_id, counterparties удалена';
GO
