import Foundation
import TeaQLCore
import TeaQLSQLite
import GeneratedTeaQL

enum VerificationError: Error { case invalidPhase, missingDatabase, wrongCount }

let phase = CommandLine.arguments.dropFirst().first ?? ""
guard ["bootstrap", "create", "read"].contains(phase) else { throw VerificationError.invalidPhase }
guard let path = ProcessInfo.processInfo.environment["SCHOOL_DATABASE"] else {
    throw VerificationError.missingDatabase
}
let service = try SQLiteDataService(path: path)
var runtime = TeaQLRuntime()
try runtime.install(GeneratedRuntimeModule.module)
let context = UserContext(runtime: runtime, actor: "school-example", trustedTenant: "school-example",
    queryExecutor: service, mutationExecutor: service, requestPolicy: RequestPolicy { $0 })
try await context.ensureSchema(GeneratedRuntimeModule.module)

if phase == "create" {
    var school = try Q.schools().comment("Initialize Riverside Primary School")
        .purpose("Verify School persistence").newEntity(context)
    school.updatePlatform(1)
    school.updateSchoolTypeToPrimary()
    school.updateName("Riverside Primary School")
    school.updateAddress("12 River Road, Springfield")
    school.updateEstablishedDate(ISO8601DateFormatter().date(from: "1995-09-01T00:00:00Z")!)
    school.updateStudentCapacity(800)
    school.updateActive(true)
    _ = try await school.auditAs("Create the documented School fixture").save(context)
}

let rows = try await Q.schoolsWithMinimalFields().selectName()
    .withNameIs("Riverside Primary School").orderByIdAscending().limit(2)
    .comment("Read the persisted School fixture").purpose("Verify School persistence")
    .executeForList(context)
guard rows.count == (phase == "bootstrap" ? 0 : 1) else { throw VerificationError.wrongCount }
print("SCHOOL_OK phase=\(phase)")
