-- ScadaLink development database setup
-- Run against a fresh MS SQL 2022 instance.
-- EF Core migrations handle schema creation; this script only creates
-- the empty databases and the application login/user.

-- Create databases
IF NOT EXISTS (SELECT name FROM sys.databases WHERE name = 'ScadaLinkConfig')
    CREATE DATABASE ScadaLinkConfig;
GO

IF NOT EXISTS (SELECT name FROM sys.databases WHERE name = 'ScadaLinkMachineData')
    CREATE DATABASE ScadaLinkMachineData;
GO

-- Create application login
IF NOT EXISTS (SELECT name FROM sys.server_principals WHERE name = 'scadalink_app')
    CREATE LOGIN scadalink_app WITH PASSWORD = 'ScadaLink_Dev1!', DEFAULT_DATABASE = ScadaLinkConfig;
GO

-- Grant db_owner on ScadaLinkConfig
USE ScadaLinkConfig;
GO
IF NOT EXISTS (SELECT name FROM sys.database_principals WHERE name = 'scadalink_app')
    CREATE USER scadalink_app FOR LOGIN scadalink_app;
GO
ALTER ROLE db_owner ADD MEMBER scadalink_app;
GO

-- Grant db_owner on ScadaLinkMachineData
USE ScadaLinkMachineData;
GO
IF NOT EXISTS (SELECT name FROM sys.database_principals WHERE name = 'scadalink_app')
    CREATE USER scadalink_app FOR LOGIN scadalink_app;
GO
ALTER ROLE db_owner ADD MEMBER scadalink_app;
GO
