using System.Data;
using Insight.Database;
using PlanTempus.Core.Database.ConnectionFactory;
using PlanTempus.Database.Common;

namespace PlanTempus.Database.Core.DCL
{

	/// <summary>
	/// Only a superadmin or similar can create Application Users
	/// </summary>
	public class SetupDbAdmin : IDbConfigure<SetupDbAdmin.Command>
	{
		public class Command
		{
			public required string Schema { get; init; }
			public required string User { get; init; }
			public required string Password { get; init; }
		}


		Command _command;
		private readonly IDbConnectionFactory _connectionFactory;

		public SetupDbAdmin(IDbConnectionFactory connectionFactory)
		{
			_connectionFactory = connectionFactory;
		}


		public void With(Command command, ConnectionStringParameters parameters = null)
		{
			_command = command;

			if (!Validations.IsValidSchemaName(_command.Schema))
				throw new ArgumentException("Invalid schema name", _command.Schema);

			using var conn = parameters is null ? _connectionFactory.Create() : _connectionFactory.Create(parameters);
			using var transaction = conn.OpenWithTransaction();
			try
			{
				CreateSchema(conn);
				CreateRole(conn);
				GrantSchemaRights(conn);

				transaction.Commit();
			}
			catch (Exception ex)
			{
				transaction.Rollback();
				throw new InvalidOperationException("Failed to SetupApplicationUser in Database", ex);
			}

		}

		private void CreateSchema(IDbConnection db)
		{
			var sql = $"CREATE SCHEMA IF NOT EXISTS {_command.Schema}";
			db.ExecuteSql(sql);
		}

		private void CreateRole(IDbConnection db)
		{
			var sql = $@"
							DO $$ 
							BEGIN
							   IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '{_command.User}') THEN
								   CREATE ROLE {_command.User} WITH CREATEDB CREATEROLE LOGIN PASSWORD '{_command.Password}';
							   END IF;
							END $$;";
			db.ExecuteSql(sql);

			var sql1 = $"ALTER ROLE {_command.User} SET search_path='{_command.Schema}';";
			db.ExecuteSql(sql1);

			var sql2 = $"ALTER SCHEMA {_command.Schema} OWNER TO {_command.User};";
			db.ExecuteSql(sql2);

		}

		private void GrantSchemaRights(IDbConnection db)
		{
			var sql = $@"GRANT CREATE ON SCHEMA {_command.Schema} TO {_command.User};";

			db.ExecuteSql(sql);

		}
	}
}
