package de.antco.projekt.dao;

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

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

public class ServiceItemDao {
    public List<ServiceItem> findAll() throws SQLException {
        List<ServiceItem> result = new ArrayList<>();
        String sql = "SELECT id, title, price FROM service_item ORDER BY id";
        try (Connection con = Database.getConnection();
             PreparedStatement ps = con.prepareStatement(sql);
             ResultSet rs = ps.executeQuery()) {
            while (rs.next()) {
                result.add(map(rs));
            }
        }
        return result;
    }

    public ServiceItem findById(int id) throws SQLException {
        String sql = "SELECT id, title, price FROM service_item 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;
        }
    }

    public void seedDefaultItems() throws SQLException {
        String countSql = "SELECT COUNT(*) FROM service_item";
        try (Connection con = Database.getConnection();
             PreparedStatement countStmt = con.prepareStatement(countSql)) {
            ResultSet rs = countStmt.executeQuery();
            if (rs.next() && rs.getLong(1) > 0) {
                return;
            }
        }
        insert("Ölwechsel", new BigDecimal("89.00"));
        insert("Bremsflüssigkeit wechseln", new BigDecimal("59.00"));
        insert("Reifen wechseln (pro Stück)", new BigDecimal("18.00"));
        insert("Klimaanlagen-Service", new BigDecimal("99.00"));
        insert("Bremsbeläge erneuern vorne", new BigDecimal("149.00"));
        insert("Zündkerzen austauschen", new BigDecimal("79.00"));
        insert("Diagnose / Fehlerspeicher auslesen", new BigDecimal("25.00"));
        insert("Arbeitszeit pro Stunde", new BigDecimal("75.00"));
    }

    private void insert(String title, BigDecimal price) throws SQLException {
        String sql = "INSERT INTO service_item(title, price) VALUES (?, ?)";
        try (Connection con = Database.getConnection();
             PreparedStatement ps = con.prepareStatement(sql)) {
            ps.setString(1, title);
            ps.setBigDecimal(2, price);
            ps.executeUpdate();
        }
    }

    private ServiceItem map(ResultSet rs) throws SQLException {
        return new ServiceItem(rs.getInt("id"), rs.getString("title"), rs.getBigDecimal("price"));
    }
}
