using System.Text;
namespace OpenWaf.Infrastructure.Persistence;
///
/// The schema DDL this build carries inside itself.
///
/// A NativeAOT binary cannot ask EF to build a model at run time — EF refuses it
/// outright — and both EnsureCreated and GenerateCreateScript go
/// through the design-time model, so the step that makes the first database in a
/// deployment has nowhere to get its SQL from. The answer here is to generate
/// that SQL from the model at build time, commit it, and embed it: the same
/// provider-shaped statements EF would have emitted, read from the binary rather
/// than re-derived from it.
///
/// The file is not hand-written and is not meant to be edited. The schema-script
/// gate regenerates it from the current model and fails when the committed copy
/// differs, which is what keeps "the same SQL" a checked claim rather than a
/// hope.
///
public static class EmbeddedSchema
{
private const string SqliteResource = "OpenWaf.Infrastructure.Persistence.Schema.schema.sqlite.sql";
///
/// The DDL for a provider, or null when this build carries none for it. The
/// caller decides what that means; it is never treated as "no schema".
///
public static string? ScriptFor(string? providerName)
=> providerName switch
{
"Microsoft.EntityFrameworkCore.Sqlite" => Read(SqliteResource),
_ => null
};
///
/// The resource names this build embeds, so the gate can enumerate them
/// instead of hard-coding the file list a second time.
///
public static IReadOnlyList ResourceNames
=> typeof(EmbeddedSchema).Assembly.GetManifestResourceNames();
private static string? Read(string resource)
{
using var stream = typeof(EmbeddedSchema).Assembly.GetManifestResourceStream(resource);
if (stream is null) return null;
using var reader = new StreamReader(stream, Encoding.UTF8);
// The generator writes a byte-order mark; sqlite parses it as the start of
// the first statement and reports a syntax error on the very first table.
return reader.ReadToEnd().TrimStart('\uFEFF');
}
}