SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO

UPDATE dbo.IllustrationLibraryItems
SET MetadataJson = JSON_MODIFY(
        JSON_MODIFY(
        JSON_MODIFY(
        JSON_MODIFY(
        JSON_MODIFY(
        JSON_MODIFY(
        JSON_MODIFY(
        JSON_MODIFY(
            CASE WHEN ISJSON(MetadataJson) = 1 THEN MetadataJson ELSE N'{}' END,
            '$.category',
            Category),
            '$.metadataConfidence',
            COALESCE(JSON_VALUE(MetadataJson, '$.metadataConfidence'), N'High')),
            '$.ageBand',
            COALESCE(JSON_VALUE(MetadataJson, '$.ageBand'), JSON_VALUE(SpecificationJson, '$.apparentAgeBand'))),
            '$.presentation',
            COALESCE(JSON_VALUE(MetadataJson, '$.presentation'), JSON_VALUE(SpecificationJson, '$.presentation'))),
            '$.hairColour',
            COALESCE(JSON_VALUE(MetadataJson, '$.hairColour'), JSON_VALUE(SpecificationJson, '$.hairColour'))),
            '$.hairLength',
            COALESCE(JSON_VALUE(MetadataJson, '$.hairLength'), JSON_VALUE(SpecificationJson, '$.hairLength'))),
            '$.skinTone',
            COALESCE(JSON_VALUE(MetadataJson, '$.skinTone'), JSON_VALUE(SpecificationJson, '$.skinTone'))),
            '$.source',
            COALESCE(JSON_VALUE(MetadataJson, '$.source'), N'specification-backfill')),
    UpdatedUtc = SYSUTCDATETIME()
WHERE Category = N'Character'
    AND IsActive = 1
    AND ISJSON(SpecificationJson) = 1
    AND (
        ISJSON(MetadataJson) <> 1
        OR JSON_VALUE(MetadataJson, '$.category') IS NULL
        OR JSON_VALUE(MetadataJson, '$.metadataConfidence') IS NULL
        OR JSON_VALUE(MetadataJson, '$.ageBand') IS NULL
        OR JSON_VALUE(MetadataJson, '$.presentation') IS NULL
        OR JSON_VALUE(MetadataJson, '$.hairColour') IS NULL
        OR JSON_VALUE(MetadataJson, '$.skinTone') IS NULL
    );
GO

UPDATE dbo.IllustrationLibraryItems
SET MetadataJson = JSON_MODIFY(
        JSON_MODIFY(
            CASE WHEN ISJSON(MetadataJson) = 1 THEN MetadataJson ELSE N'{}' END,
            '$.category',
            Category),
            '$.metadataConfidence',
            COALESCE(JSON_VALUE(MetadataJson, '$.metadataConfidence'), N'High')),
    UpdatedUtc = SYSUTCDATETIME()
WHERE Category IN (N'Location', N'Asset')
    AND IsActive = 1
    AND (
        ISJSON(MetadataJson) <> 1
        OR JSON_VALUE(MetadataJson, '$.category') IS NULL
        OR JSON_VALUE(MetadataJson, '$.metadataConfidence') IS NULL
    );
GO
