package de.antco.projekt.dao;

import de.antco.projekt.Database;
import de.antco.projekt.model.Vehicle;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class VehicleDao {
    public Vehicle create(int personId, String brand, String model, String plate) throws SQLException {
        String sql = "INSERT INTO vehicle(person_id, brand, model, plate) VALUES (?, ?, ?, ?) RETURNING id";
        try (Connection con = Database.getConnection();
             PreparedStatement ps = con.prepareStatement(sql)) {
            ps.setInt(1, personId);
            ps.setString(2, brand);
            ps.setString(3, model);
            ps.setString(4, plate);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                return new Vehicle(rs.getInt("id"), personId, brand, model, plate);
            }
            throw new SQLException("Konnte Fahrzeug nicht speichern");
        }
    }

    public List<Vehicle> findByPerson(int personId) throws SQLException {
        List<Vehicle> result = new ArrayList<>();
        String sql = "SELECT id, person_id, brand, model, plate FROM vehicle WHERE person_id = ? ORDER BY id";
        try (Connection con = Database.getConnection();
             PreparedStatement ps = con.prepareStatement(sql)) {
            ps.setInt(1, personId);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                result.add(map(rs));
            }
        }
        return result;
    }

    public Vehicle findById(int id) throws SQLException {
        String sql = "SELECT id, person_id, brand, model, plate FROM vehicle WHERE id = ?";
        try (Connection con = Database.getConnection();
             PreparedStatement ps = con.prepareStatement(sql)) {
            ps.setInt(1, id);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                return map(rs);
            }
            return null;
        }
    }

    private Vehicle map(ResultSet rs) throws SQLException {
        return new Vehicle(
                rs.getInt("id"),
                rs.getInt("person_id"),
                rs.getString("brand"),
                rs.getString("model"),
                rs.getString("plate")
        );
    }
}
