-- ScadaBridge 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 = 'ScadaBridgeConfig')
    CREATE DATABASE ScadaBridgeConfig;
GO

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

-- Create application login
IF NOT EXISTS (SELECT name FROM sys.server_principals WHERE name = 'scadabridge_app')
    CREATE LOGIN scadabridge_app WITH PASSWORD = 'ScadaBridge_Dev1#', DEFAULT_DATABASE = ScadaBridgeConfig;
GO

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

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