-- MS SQL Server User Setup for Weather Connect
-- Run this as a user with appropriate privileges (e.g., sa or sysadmin role)
-- This creates a SQL Server login and database user

USE master;
GO

-- 1. Create SQL Server Login (if it doesn't exist)
IF NOT EXISTS (SELECT name FROM sys.server_principals WHERE name = 'weather_user')
BEGIN
    CREATE LOGIN weather_user WITH PASSWORD = 'Weather123!';
    PRINT 'Login weather_user created successfully.';
END
ELSE
BEGIN
    PRINT 'Login weather_user already exists.';
END
GO

-- 2. Switch to the WeatherDB database
USE WeatherDB;
GO

-- 3. Create database user for the login (if it doesn't exist)
IF NOT EXISTS (SELECT name FROM sys.database_principals WHERE name = 'weather_user')
BEGIN
    CREATE USER weather_user FOR LOGIN weather_user;
    PRINT 'User weather_user created successfully in WeatherDB.';
END
ELSE
BEGIN
    PRINT 'User weather_user already exists in WeatherDB.';
END
GO

-- 4. Grant necessary permissions to the user
-- Grant db_datareader and db_datawriter roles
ALTER ROLE db_datareader ADD MEMBER weather_user;
ALTER ROLE db_datawriter ADD MEMBER weather_user;
GO

-- Grant DDL permissions to create tables and indexes
GRANT CREATE TABLE TO weather_user;
GRANT CREATE VIEW TO weather_user;
GRANT ALTER ON SCHEMA::dbo TO weather_user;
GO

-- 5. Verify user and permissions
SELECT 
    dp.name AS UserName,
    dp.type_desc AS UserType,
    sp.name AS LoginName
FROM sys.database_principals dp
LEFT JOIN sys.server_principals sp ON dp.sid = sp.sid
WHERE dp.name = 'weather_user';
GO

-- Display granted permissions
SELECT 
    USER_NAME(grantee_principal_id) AS UserName,
    permission_name,
    state_desc
FROM sys.database_permissions
WHERE USER_NAME(grantee_principal_id) = 'weather_user'
    AND permission_name IN ('CREATE TABLE', 'CREATE VIEW', 'ALTER')
ORDER BY permission_name;
GO

-- Display role memberships
SELECT 
    USER_NAME(drm.member_principal_id) AS UserName,
    USER_NAME(drm.role_principal_id) AS RoleName
FROM sys.database_role_members drm
WHERE USER_NAME(drm.member_principal_id) = 'weather_user';
GO

PRINT 'User weather_user is ready to use.';
PRINT 'Connection string example:';
PRINT 'Server=your_server;Database=WeatherDB;User Id=weather_user;Password=Weather123!;';
GO
