using Insight.Database;
using Microsoft.ApplicationInsights;
using PlanTempus.Core.Database;
using PlanTempus.Core.Telemetry;

namespace PlanTempus.Components.Organizations.Create
{
    public class CreateOrganizationHandler(TelemetryClient telemetryClient, IDatabaseOperations databaseOperations)
    {
        public async Task<CreateOrganizationResult> Handle(CreateOrganizationCommand command)
        {
            using var db = databaseOperations.CreateScope(nameof(CreateOrganizationHandler));
            using var transaction = db.Connection.BeginTransaction();
            try
            {
                var createOrg = @"
                INSERT INTO organizations (connection_string) 
                VALUES (@ConnectionString)
                RETURNING id, created_at";

                var data = await db.Connection.QuerySqlAsync<CreateOrganizationResult>(createOrg, new
                {
                    command.ConnectionString
                });

                var orgResult = data.First();

                await db.Connection.ExecuteAsync(@$"
                INSERT INTO account_organizations (account_id, organization_id)
                VALUES (@AccountId, @OrganizationId)",
                    new { command.AccountId, OrganizationId = orgResult.Id });

                transaction.Commit();

                telemetryClient.TrackTrace(GetType().Name, orgResult.Format());
                return orgResult;
            }
            catch (Exception ex)
            {
                db.Error(ex);
                throw;
            }
        }
    }
}