using System.Data;
using Configuration;
using Microsoft.Data.SqlClient;
using Models;

namespace Services
{
    public interface IRentService
    {
        void RentCar(long customerId,long vehicleId, DateTime start, DateTime end);
        List<Vehicle> GetAvailableCars();
        List<Customer> GetCustomers();
    }

    public class RentService(SqlConnectionFactory sqlConnectionFactory) : IRentService
    {
        public List<Vehicle> GetAvailableCars()
        {
            List<Vehicle> vehicles = new List<Vehicle>();

            using SqlConnection conn = sqlConnectionFactory.CreateSqlConnection();
            string sql = "SELECT * FROM v_VerfuegbareFahrzeuge;";
            SqlCommand cmd = new SqlCommand(sql, conn);

            using SqlDataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                vehicles.Add(Vehicle.FromReader(reader));
            }

            return vehicles;
        }

        public List<Customer> GetCustomers()
        {
            List<Customer> customers = new List<Customer>();
            
            using SqlConnection conn = sqlConnectionFactory.CreateSqlConnection();
            string sql = "SELECT * FROM Customer;";
            SqlCommand cmd = new SqlCommand(sql, conn);

            using SqlDataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                customers.Add(Customer.FromReader(reader));
            }
        
            return customers;
        }

        public void RentCar(long customerId, long vehicleId, DateTime start, DateTime end)
        {
        
            using SqlConnection conn = sqlConnectionFactory.CreateSqlConnection();
            using SqlCommand cmd = new SqlCommand("sp_MieteFahrzeug", conn);
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.AddWithValue("@KundeID", customerId);
            cmd.Parameters.AddWithValue("@FahrzeugID", vehicleId);
            cmd.Parameters.AddWithValue("@Start", start);
            cmd.Parameters.AddWithValue("@Ende", end);

            cmd.ExecuteNonQuery();
        }
    }
}