SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO

DECLARE @OtherCategoryID int = (
    SELECT TOP (1) RelationshipCategoryID
    FROM dbo.RelationshipCategories
    WHERE CategoryName = N'Other'
    ORDER BY RelationshipCategoryID
);

DECLARE @FamilyCategoryID int = (
    SELECT TOP (1) RelationshipCategoryID
    FROM dbo.RelationshipCategories
    WHERE CategoryName = N'Family'
    ORDER BY RelationshipCategoryID
);

DECLARE @FriendshipCategoryID int = (
    SELECT TOP (1) RelationshipCategoryID
    FROM dbo.RelationshipCategories
    WHERE CategoryName = N'Friendship'
    ORDER BY RelationshipCategoryID
);

DECLARE @RomanticCategoryID int = (
    SELECT TOP (1) RelationshipCategoryID
    FROM dbo.RelationshipCategories
    WHERE CategoryName = N'Romantic / Sexual'
    ORDER BY RelationshipCategoryID
);

DECLARE @HostileCategoryID int = (
    SELECT TOP (1) RelationshipCategoryID
    FROM dbo.RelationshipCategories
    WHERE CategoryName = N'Hostile / Conflict'
    ORDER BY RelationshipCategoryID
);

DECLARE @ProfessionalCategoryID int = (
    SELECT TOP (1) RelationshipCategoryID
    FROM dbo.RelationshipCategories
    WHERE CategoryName = N'Professional / Social'
    ORDER BY RelationshipCategoryID
);

MERGE dbo.RelationshipTypes AS target
USING (VALUES
    (N'Unknown', 0, 1, @OtherCategoryID),
    (N'Family', 1, 2, @FamilyCategoryID),
    (N'Friend', 0, 3, @FriendshipCategoryID),
    (N'Romantic', 0, 4, @RomanticCategoryID),
    (N'Professional', 0, 5, @ProfessionalCategoryID),
    (N'Educational', 0, 6, @ProfessionalCategoryID),
    (N'Authority', 0, 7, @ProfessionalCategoryID),
    (N'Criminal', 0, 8, @HostileCategoryID),
    (N'Medical', 0, 9, @ProfessionalCategoryID),
    (N'Neighbour', 0, 10, @ProfessionalCategoryID),
    (N'Ally', 0, 11, @FriendshipCategoryID),
    (N'Rival', 0, 12, @HostileCategoryID)
) AS source (TypeName, IsPermanentDefault, SortOrder, RelationshipCategoryID)
ON target.TypeName = source.TypeName
WHEN MATCHED THEN
    UPDATE SET
        target.IsPermanentDefault = source.IsPermanentDefault,
        target.SortOrder = source.SortOrder,
        target.IsActive = 1,
        target.RelationshipCategoryID = COALESCE(source.RelationshipCategoryID, target.RelationshipCategoryID)
WHEN NOT MATCHED THEN
    INSERT (TypeName, IsPermanentDefault, SortOrder, IsActive, RelationshipCategoryID)
    VALUES (source.TypeName, source.IsPermanentDefault, source.SortOrder, 1, source.RelationshipCategoryID);
GO
