package main

import (
    "fmt"
    "os"
    "time"
    lib "school-management-service-core-workspace/lib"
)

func main() {
    if err := run(); err != nil { panic(err) }
}

func run() error {
    if len(os.Args) != 2 { return fmt.Errorf("expected bootstrap, create or read") }
    phase := os.Args[1]
    if phase != "bootstrap" && phase != "create" && phase != "read" {
        return fmt.Errorf("unknown phase %q", phase)
    }
    context, err := lib.ServiceRuntimeFromEnv()
    if err != nil { return err }
    if err := lib.EnsureSchema(context); err != nil { return err }

    if phase == "create" {
        school := lib.Q.Schools().Comment("Initialize Riverside Primary School").
            Purpose("Verify School persistence").NewEntity(context)
        school.UpdatePlatformId(1)
        school.UpdateSchoolTypeToPrimary()
        school.UpdateName("Riverside Primary School")
        school.UpdateAddress("12 River Road, Springfield")
        school.UpdateEstablishedDate(time.Date(1995, 9, 1, 0, 0, 0, 0, time.UTC))
        school.UpdateStudentCapacity(800)
        school.UpdateActive(true)
        if _, err := school.AuditAs("Create the documented School fixture").Save(context); err != nil {
            return err
        }
    }

    rows, err := lib.Q.SchoolsMinimal().SelectName().
        WithNameIs("Riverside Primary School").OrderByIdAsc().Limit(2).
        Comment("Read the persisted School fixture").Purpose("Verify School persistence").
        ExecuteForList(context)
    if err != nil { return err }
    expected := 1
    if phase == "bootstrap" { expected = 0 }
    if len(rows.Data) != expected { return fmt.Errorf("School count: got %d, want %d", len(rows.Data), expected) }
    fmt.Printf("SCHOOL_OK phase=%s\n", phase)
    return nil
}
