using System.Data;
using Microsoft.Data.SqlClient;
using NT.AltText.Models;
using NT.AltText.Repository.Database;
using NT.AltText.Repository.Interfaces;
using NT.AltText.Repository.Models;

namespace NT.AltText.Repository
{
    public class AnalysisRepository : IAnalysisRepository
    {
        private string connectionString = AltTextDbConnection.GetConnection();

        public async Task<int> AddAnalysis(Analysis analysis)
        {
        
            using var conn = new SqlConnection(connectionString);
            using var cmd = new SqlCommand(SpNames.AddAnalysis, conn)
            {
                CommandType = CommandType.StoredProcedure
            };

            // Add input parameters, convert null-coalescing to DBNull.Value
            cmd.Parameters.AddWithValue("@JobId", (object?)analysis.JobId ?? DBNull.Value);
            cmd.Parameters.AddWithValue("@VendorAssignment", (object?)analysis.VendorAssignment ?? DBNull.Value);
            cmd.Parameters.AddWithValue("@DesciplineId", (object?)analysis.DesciplineId ?? DBNull.Value);
            cmd.Parameters.AddWithValue("@SubDesciplineId", (object?)analysis.SubDesciplineId ?? DBNull.Value);
            cmd.Parameters.AddWithValue("@Status", (object?)analysis.Status ?? DBNull.Value);
            cmd.Parameters.AddWithValue("@Complexity", (object?)analysis.Complexity ?? DBNull.Value);
            cmd.Parameters.AddWithValue("@ReviewerId", (object?)analysis.ReviewerId ?? DBNull.Value);
            cmd.Parameters.AddWithValue("@ReviewerName", (object?)analysis.ReviewerName ?? DBNull.Value);
            cmd.Parameters.AddWithValue("@AnchorId", (object?)analysis.AnchorId ?? DBNull.Value);
            cmd.Parameters.AddWithValue("@AnchorName", (object?)analysis.AnchorName ?? DBNull.Value);
            cmd.Parameters.AddWithValue("@WriteId", (object?)analysis.WriteId ?? DBNull.Value);
            cmd.Parameters.AddWithValue("@WriterName", (object?)analysis.WriterName ?? DBNull.Value);
            cmd.Parameters.AddWithValue("@CatsheetPreperationId", (object?)analysis.CatsheetPreperationId ?? DBNull.Value);
            cmd.Parameters.AddWithValue("@CatsheetPreparationName", (object?)analysis.CatsheetPreparationName ?? DBNull.Value);
            //await conn.OpenAsync().ConfigureAwait(false);
            //return await cmd.ExecuteNonQueryAsync().ConfigureAwait(false);


            var outputIdParam = new SqlParameter("@NewId", SqlDbType.Int)
            {
                Direction = ParameterDirection.Output
            };
            cmd.Parameters.Add(outputIdParam);

            await conn.OpenAsync().ConfigureAwait(false);
            await cmd.ExecuteNonQueryAsync().ConfigureAwait(false);

            // Safely extract output value
            var result = (outputIdParam.Value == DBNull.Value)
                ? 0
                : (int)outputIdParam.Value;

            return result;
        
    }

       

   


    }
}
