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) throws SQLException {
        String sql = "INSERT INTO person(name, phone) VALUES (?, ?) RETURNING id";
        try (Connection con = Database.getConnection();
             PreparedStatement ps = con.prepareStatement(sql)) {
            ps.setString(1, name);
            ps.setString(2, phone);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                return new Person(rs.getInt("id"), name, phone);
            }
            throw new SQLException("Konnte Person nicht speichern");
        }
    }

    public List<Person> findAll() throws SQLException {
        List<Person> result = new ArrayList<>();
        String sql = "SELECT id, name, phone 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")));
            }
        }
        return result;
    }

    public Person findById(int id) throws SQLException {
        String sql = "SELECT id, name, phone 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"));
            }
            return null;
        }
    }
}
