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 JobRepository :IJobRepository
    {
        private string connectionString = AltTextDbConnection.GetConnection();
        public async Task<int> AddJobAsync(JobDetails job)
        {
            using var conn = new SqlConnection(connectionString);
            using var cmd = new SqlCommand(SpNames.AddJobMaster, conn)
            {
                CommandType = CommandType.StoredProcedure
            };

            // Add input parameters, convert null-coalescing to DBNull.Value
            cmd.Parameters.AddWithValue("@JobId", (object?)job.JobId ?? DBNull.Value);
            cmd.Parameters.AddWithValue("@Author", (object?)job.Author ?? DBNull.Value);
            cmd.Parameters.AddWithValue("@Title", (object?)job.Title ?? DBNull.Value);
            cmd.Parameters.AddWithValue("@Specification", (object?)job.Specification ?? DBNull.Value);
            cmd.Parameters.AddWithValue("@FilePathWithExtension", (object?)job.FilePathWithExtension ?? DBNull.Value);
            cmd.Parameters.AddWithValue("@ReceivedDate", job.ReceivedDate);
            cmd.Parameters.AddWithValue("@ScheduledDate", job.ScheduledDate);
            cmd.Parameters.AddWithValue("@CustomerDate", job.CustomerDueDate);
            cmd.Parameters.AddWithValue("@StartDate", job.StartDate);
            cmd.Parameters.AddWithValue("@EndDate", job.EndDate);
            cmd.Parameters.AddWithValue("@AssignedById", job.AssignedById);
            cmd.Parameters.AddWithValue("@AssignedByName", (object?)job.AssignedByName ?? DBNull.Value);

            // Define output parameter
            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;
        }

        public Task<bool> DeleteJobAsync(int id)
        {
            throw new NotImplementedException();
        }

        public Task<IEnumerable<JobDetails>> GetAllJobsAsync() 
        {
            throw new NotImplementedException();
        }

        public Task<JobDetails?> GetJobByIdAsync(int id)
        {
            throw new NotImplementedException();
        }

        public Task<JobDetails?> UpdateJobAsync(int id, JobDetails job)
        {
            throw new NotImplementedException();
        }

        
       
    }
}
