select 'post_deployment_script';

SET QUOTED_IDENTIFIER ON; -- IMPORTANT TO ADD IN ALL DEPLOYS
GO

BEGIN
/*
    Initialize EQP initial metric values for Caster molds in spares.
    Source: CAS.StrandData heat count per MoldId.

    This sets InitialAbsoluteValue so that when a mold is installed on a strand,
    its Total in EQP starts from the correct historical value.

    Run once. Safe to re-run (uses MERGE via EQPSetInitialMetricValue).
    Date: 2026-04-02
*/

SET NOCOUNT ON

DECLARE @MetricTypeId INT
SELECT @MetricTypeId = MetricTypeId FROM EQP.catMetricTypes WHERE MetricTypeName = 'Heats'

-- Calculate heats per spare mold from CAS.StrandData
DECLARE @MoldHeats TABLE (PartId INT PRIMARY KEY, HeatsFromCAS INT)

INSERT INTO @MoldHeats (PartId, HeatsFromCAS)
SELECT
    p.PartId,
    COUNT(sd.ProcessId) AS HeatsFromCAS
FROM EQP.catParts p
INNER JOIN EQP.catPartTypes pt ON pt.PartTypeId = p.PartTypeId
INNER JOIN EQP.fLastMovement(NULL) lm ON lm.PartId = p.PartId
INNER JOIN EQP.catParts parent ON parent.PartId = lm.ParentPartId
INNER JOIN CAS.StrandData sd ON sd.MoldId = p.AuxPartId
WHERE pt.PartTypeName = 'Mold'
  AND parent.IsDefaultArray = 1
GROUP BY p.PartId

-- Upsert initial values
MERGE EQP.catPartInitialValues AS piv
USING @MoldHeats AS src
    ON piv.PartId = src.PartId AND piv.MetricTypeId = @MetricTypeId
WHEN MATCHED AND piv.InitialAbsoluteValue != src.HeatsFromCAS THEN
    UPDATE SET InitialAbsoluteValue = src.HeatsFromCAS,
               InitialTotalValue = src.HeatsFromCAS,
               InitialPartialValue = src.HeatsFromCAS
WHEN NOT MATCHED THEN
    INSERT (PartId, MetricTypeId, InitialAbsoluteValue, InitialTotalValue, InitialPartialValue)
    VALUES (src.PartId, @MetricTypeId, src.HeatsFromCAS, src.HeatsFromCAS, src.HeatsFromCAS);

-- Report
SELECT p.PartName, mh.HeatsFromCAS AS InitialValue
FROM @MoldHeats mh
INNER JOIN EQP.catParts p ON p.PartId = mh.PartId
ORDER BY p.PartName

PRINT 'Done: ' + CAST(@@ROWCOUNT AS VARCHAR) + ' molds initialized'

END
