package de.antco.projekt.dao;

import de.antco.projekt.Database;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

public class SchemaCreator {
    public void ensureSchema() throws SQLException {
        try (Connection con = Database.getConnection(); Statement st = con.createStatement()) {
            st.execute("CREATE TABLE IF NOT EXISTS person (" +
                    "id SERIAL PRIMARY KEY, " +
                    "name VARCHAR(200) NOT NULL, " +
                    "phone VARCHAR(100), " +
                    "email VARCHAR(200), " +
                    "address VARCHAR(255)" +
                    ")");
            
            // Migration: Add columns if they don't exist (using simplistic approach catching errors if column exists or using IF NOT EXISTS syntax if supported by DB)
            // Postgres supports IF NOT EXISTS for ADD COLUMN in newer versions. 
            // To be safe and simple in JDBC without specific version check, we can try to add and ignore exception or check metadata.
            // But here I'll assume Postgres which supports: ALTER TABLE ... ADD COLUMN IF NOT EXISTS ...
            try {
                st.execute("ALTER TABLE person ADD COLUMN IF NOT EXISTS email VARCHAR(200)");
                st.execute("ALTER TABLE person ADD COLUMN IF NOT EXISTS address VARCHAR(255)");
            } catch (SQLException ignored) {
                // Ignore if syntax is not supported or other non-critical error during migration attempt
            }

            st.execute("CREATE TABLE IF NOT EXISTS vehicle (" +
                    "id SERIAL PRIMARY KEY, " +
                    "person_id INTEGER NOT NULL REFERENCES person(id) ON DELETE CASCADE, " +
                    "brand VARCHAR(120) NOT NULL, " +
                    "model VARCHAR(120) NOT NULL, " +
                    "plate VARCHAR(50) NOT NULL" +
                    ")");
            st.execute("CREATE TABLE IF NOT EXISTS service_item (" +
                    "id SERIAL PRIMARY KEY, " +
                    "title VARCHAR(200) NOT NULL, " +
                    "price NUMERIC(10,2) NOT NULL" +
                    ")");
            st.execute("CREATE TABLE IF NOT EXISTS work_order (" +
                    "id SERIAL PRIMARY KEY, " +
                    "vehicle_id INTEGER NOT NULL REFERENCES vehicle(id) ON DELETE CASCADE, " +
                    "note TEXT, " +
                    "created_at TIMESTAMP NOT NULL DEFAULT NOW()" +
                    ")");
            st.execute("CREATE TABLE IF NOT EXISTS work_order_item (" +
                    "id SERIAL PRIMARY KEY, " +
                    "work_order_id INTEGER NOT NULL REFERENCES work_order(id) ON DELETE CASCADE, " +
                    "service_item_id INTEGER NOT NULL REFERENCES service_item(id), " +
                    "quantity INTEGER NOT NULL" +
                    ")");
        }
    }
}
