package io.teaql.examples.reference;

import io.teaql.core.UserContext;
import io.teaql.core.meta.SimpleEntityMetaFactory;
import io.teaql.core.reference.ContextBoundDocumentService.*;
import io.teaql.core.reference.*;
import io.teaql.runtime.DefaultUserContext;
import io.teaql.runtime.TeaQLRuntime;
import io.teaql.secure.document.reference.*;
import java.nio.file.*;
import java.security.SecureRandom;
import java.sql.*;
import java.time.Duration;
import java.util.*;

/** Application-owned terminal demo, using the companion SQLite document service. */
public final class OrderEditExample {
    private static final String NUMBER = "ORDER-1001";
    private static final String PURPOSE = SqliteOrderDocumentService.PURPOSE;
    private final String url;
    private final byte[] key = new byte[32];
    private final List<TeaQLRuntime> runtimes = new ArrayList<>();
    private OrderEditExample(Path database) {
        url = "jdbc:sqlite:" + database;
        new SecureRandom().nextBytes(key);
    }
    public static void main(String[] args) throws Exception {
        Path root = Files.createTempDirectory("teaql-order-edit-guide-");
        var demo = new OrderEditExample(root.resolve("orders.sqlite"));
        try { demo.run(); }
        finally {
            for (var runtime : demo.runtimes) runtime.close();
            try (var paths = Files.walk(root)) {
                for (var path : paths.sorted(Comparator.reverseOrder()).toList()) Files.deleteIfExists(path);
            }
        }
    }
    private void run() throws Exception {
        schemaAndFixture();
        UserContext alice = context("alice");
        ContextualDocument opened = alice.openDocument(new OpenRequest(
            "Order", NUMBER, PURPOSE, Duration.ofMinutes(15)));
        require(rows(opened).size() == 2);
        require(!opened.body().containsKey("id"));
        require(!rows(opened).get(0).containsKey("id"));
        System.out.println("PASS open: business ID, editable body and protected token; no raw row IDs");

        Map<String,Object> forged = edit(opened, 5, false);
        @SuppressWarnings("unchecked")
        var forgedRows = (List<Map<String,Object>>) forged.get("items");
        forgedRows.get(0).put("productName", "Forged name");
        fails(RoundTripReferenceErrorCode.DOCUMENT_PROJECTION_VIOLATION,
            () -> alice.acceptDocument(request(opened, "forged", forged)));
        Map<String,Object> missing = edit(opened, 5, false);
        @SuppressWarnings("unchecked")
        var missingRows = (List<Map<String,Object>>) missing.get("items");
        missingRows.remove(1);
        fails(RoundTripReferenceErrorCode.DOCUMENT_PROJECTION_VIOLATION,
            () -> alice.acceptDocument(request(opened, "missing", missing)));
        require(scalar("SELECT count(*) FROM document_commands") == 0);
        System.out.println("PASS projection: read-only field changes and implicit row removal rejected");

        UserContext bob = context("bob");
        fails(RoundTripReferenceErrorCode.SCOPE_MISMATCH,
            () -> bob.acceptDocument(request(opened, "bob", edit(opened, 5, false))));
        System.out.println("PASS actor: another user cannot submit Alice's document");

        AcceptRequest command = request(opened, "edit-1", edit(opened, 5, false));
        sql("CREATE TRIGGER fail_item BEFORE UPDATE ON order_items BEGIN SELECT RAISE(ABORT,'demo failure'); END");
        fails(RoundTripReferenceErrorCode.DOCUMENT_VALIDATION_FAILED,
            () -> alice.acceptDocument(command));
        require(scalar("SELECT version FROM orders WHERE id=10") == 1);
        require(scalar("SELECT quantity FROM order_items WHERE id=101") == 2);
        require(scalar("SELECT count(*) FROM document_commands") == 0);
        sql("DROP TRIGGER fail_item");
        System.out.println("PASS rollback: failed child write leaves order, quantity and receipt unchanged");

        AcceptedDocument accepted = alice.acceptDocument(command);
        require(accepted.previousRevision() == 1 && accepted.newRevision() == 2);
        require(scalar("SELECT quantity FROM order_items WHERE id=101") == 5);
        require(scalar("SELECT count(*) FROM order_items") == 2);
        require(scalar("SELECT count(*) FROM document_commands") == 1);
        System.out.println("PASS accept: quantity 2 to 5; revision 1 to 2; one durable receipt");

        // A fresh request context uses the same server-held key and current permission checks.
        UserContext retryContext = context("alice");
        AcceptedDocument replayed = retryContext.acceptDocument(command);
        require(replayed.document().documentToken().equals(accepted.document().documentToken()));
        require(scalar("SELECT version FROM orders WHERE id=10") == 2);
        require(scalar("SELECT count(*) FROM document_commands") == 1);
        fails(RoundTripReferenceErrorCode.DOCUMENT_COMMAND_CONFLICT,
            () -> retryContext.acceptDocument(request(opened, "edit-1", edit(opened, 6, false))));
        System.out.println("PASS retry: identical command returns first result; changed payload conflicts");

        fails(RoundTripReferenceErrorCode.DOCUMENT_REVISION_CONFLICT,
            () -> alice.acceptDocument(request(opened, "stale-edit", edit(opened, 6, false))));
        require(scalar("SELECT quantity FROM order_items WHERE id=101") == 5);
        System.out.println("PASS stale: a new command against the old document cannot overwrite the saved edit");

        ContextualDocument next = accepted.document();
        AcceptedDocument removed = alice.acceptDocument(request(next, "remove-1", edit(next, 5, true)));
        require(removed.newRevision() == 3);
        require(scalar("SELECT count(*) FROM order_items WHERE id=102") == 0);
        require(scalar("SELECT count(*) FROM order_items WHERE id=101") == 1);
        System.out.println("PASS remove: refreshed document and explicit removedRefs delete only the selected row");

        sql("UPDATE document_permissions SET can_edit=0 WHERE subject='alice'");
        fails(RoundTripReferenceErrorCode.AUTHORIZATION_REQUIRED,
            () -> alice.openDocument(new OpenRequest("Order", NUMBER, PURPOSE, Duration.ofMinutes(15))));
        fails(RoundTripReferenceErrorCode.AUTHORIZATION_REQUIRED,
            () -> retryContext.acceptDocument(command));
        require(scalar("SELECT version FROM orders WHERE id=10") == 3);
        require(scalar("SELECT count(*) FROM document_commands") == 2);
        System.out.println("PASS revocation: current permission denies both new open and committed-command replay");
    }
    private UserContext context(String subject) {
        var provider = AeadRoundTripReferenceProvider.governed(
            DeploymentProfile.DEVELOPMENT, "order-edit-guide", "local-demo",
            new StaticRoundTripReferenceKeyProvider(new RoundTripReferenceKey("demo-key", key)),
            (ctx, principal, scope, identity) -> {
                if (!"Customer".equals(principal.domainRootType()) || principal.domainRootId() != 7
                        || !"Order".equals(scope.aggregateType()) || scope.aggregateId() != 10
                        || grant(principal.subject()) != 1) {
                    throw new RoundTripReferenceException(RoundTripReferenceErrorCode.AUTHORIZATION_REQUIRED,
                        "AUTHORIZATION_REQUIRED");
                }
            });
        var runtime = SecureDocumentReferenceModule.of(provider)
            .installInto(TeaQLRuntime.builder().metadata(new SimpleEntityMetaFactory())).build();
        runtimes.add(runtime);
        return new DefaultUserContext(runtime)
            .withTrustedReferencePrincipal(new TrustedReferencePrincipal("demo-auth", subject, "Customer", 7))
            .withContextBoundDocumentService(new SqliteOrderDocumentService(url));
    }
    @SuppressWarnings("unchecked")
    private static List<Map<String,Object>> rows(ContextualDocument document) {
        return (List<Map<String,Object>>) document.body().get("items");
    }
    private static Map<String,Object> edit(ContextualDocument document, long quantity, boolean removeSecond) {
        List<Map<String,Object>> copy = new ArrayList<>();
        List<String> removed = new ArrayList<>();
        for (int index=0; index<rows(document).size(); index++) {
            Map<String,Object> row = new LinkedHashMap<>(rows(document).get(index));
            if (index == 1 && removeSecond) { removed.add((String) row.get("ref")); continue; }
            if (index == 0) row.put("quantity", quantity);
            copy.add(row);
        }
        Map<String,Object> body = new LinkedHashMap<>();
        body.put("orderNumber", document.businessId()); body.put("items", copy); body.put("removedRefs", removed);
        return body;
    }
    private static AcceptRequest request(ContextualDocument document, String commandId, Map<String,Object> body) {
        return new AcceptRequest("Order", PURPOSE,
            new SubmittedDocument(document.businessId(), document.documentToken(), commandId, body));
    }
    private int grant(String subject) {
        try (Connection c=DriverManager.getConnection(url);
             PreparedStatement q=c.prepareStatement("SELECT can_edit FROM document_permissions WHERE subject=? AND customer_id=7")) {
            q.setString(1, subject);
            try (ResultSet rows=q.executeQuery()) { return rows.next() ? rows.getInt(1) : 0; }
        } catch (SQLException failed) { throw new IllegalStateException("Demo permission lookup failed", failed); }
    }
    private void schemaAndFixture() throws SQLException {
        sql("CREATE TABLE orders(id INTEGER PRIMARY KEY, version INTEGER NOT NULL, customer_id INTEGER NOT NULL, order_number TEXT NOT NULL UNIQUE)");
        sql("CREATE TABLE order_items(id INTEGER PRIMARY KEY, order_id INTEGER NOT NULL, version INTEGER NOT NULL, product_name TEXT NOT NULL, sku TEXT NOT NULL, quantity INTEGER NOT NULL)");
        sql("CREATE TABLE document_permissions(subject TEXT NOT NULL, customer_id INTEGER NOT NULL, can_edit INTEGER NOT NULL, PRIMARY KEY(subject,customer_id))");
        sql("CREATE TABLE document_commands(subject TEXT NOT NULL, command_id TEXT NOT NULL, digest BLOB NOT NULL, previous_version INTEGER NOT NULL, new_version INTEGER NOT NULL, changed_entities TEXT NOT NULL, result_token TEXT NOT NULL, result_body TEXT NOT NULL, PRIMARY KEY(subject,command_id))");
        sql("INSERT INTO orders VALUES(10,1,7,'ORDER-1001')");
        sql("INSERT INTO order_items VALUES(101,10,1,'Blue cup','CUP-1',2)");
        sql("INSERT INTO order_items VALUES(102,10,1,'Red cup','CUP-2',3)");
        sql("INSERT INTO document_permissions VALUES('alice',7,1)");
    }
    private void sql(String text) throws SQLException {
        try (Connection c=DriverManager.getConnection(url); Statement s=c.createStatement()) { s.execute(text); }
    }
    private long scalar(String text) throws SQLException {
        try (Connection c=DriverManager.getConnection(url); Statement s=c.createStatement(); ResultSet r=s.executeQuery(text)) {
            require(r.next()); return r.getLong(1);
        }
    }
    private static void fails(RoundTripReferenceErrorCode expected, Runnable action) {
        try { action.run(); }
        catch (RoundTripReferenceException failed) { require(failed.getCode() == expected); return; }
        throw new IllegalStateException("Expected rejection: " + expected);
    }
    private static void require(boolean condition) {
        if (!condition) throw new IllegalStateException("Order editing example assertion failed");
    }
}
