package de.antco.projekt.dao;

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

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

public class PersonDao {
    public Person create(String name, String phone, String email, String address) throws SQLException {
        String sql = "INSERT INTO person(name, phone, email, address) VALUES (?, ?, ?, ?) RETURNING id";
        try (Connection con = Database.getConnection();
             PreparedStatement ps = con.prepareStatement(sql)) {
            ps.setString(1, name);
            ps.setString(2, phone);
            ps.setString(3, email);
            ps.setString(4, address);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                return new Person(rs.getInt("id"), name, phone, email, address);
            }
            throw new SQLException("Konnte Person nicht speichern");
        }
    }

    public List<Person> findAll() throws SQLException {
        List<Person> result = new ArrayList<>();
        String sql = "SELECT id, name, phone, email, address FROM person ORDER BY name";
        try (Connection con = Database.getConnection();
             PreparedStatement ps = con.prepareStatement(sql);
             ResultSet rs = ps.executeQuery()) {
            while (rs.next()) {
                result.add(new Person(
                    rs.getInt("id"), 
                    rs.getString("name"), 
                    rs.getString("phone"),
                    rs.getString("email"),
                    rs.getString("address")
                ));
            }
        }
        return result;
    }

    public Person findById(int id) throws SQLException {
        String sql = "SELECT id, name, phone, email, address FROM person WHERE id = ?";
        try (Connection con = Database.getConnection();
             PreparedStatement ps = con.prepareStatement(sql)) {
            ps.setInt(1, id);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                return new Person(
                    rs.getInt("id"), 
                    rs.getString("name"), 
                    rs.getString("phone"),
                    rs.getString("email"),
                    rs.getString("address")
                );
            }
            return null;
        }
    }
}
