import Foundation
import SwiftData

public enum SharedStore {
    public static let appGroupID = "group.com.conjuga.app"

    /// Resolves the local SwiftData store URL inside the shared app group container
    /// at the canonical `Library/Application Support/local.store` path.
    /// Returns nil if the app group isn't accessible (entitlement / profile issue).
    public static func localStoreURL() -> URL? {
        guard let groupURL = FileManager.default.containerURL(
            forSecurityApplicationGroupIdentifier: appGroupID
        ) else {
            return nil
        }
        let dir = groupURL.appendingPathComponent("Library/Application Support")
        try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
        return dir.appendingPathComponent("local.store")
    }

    /// Global reference to the main app's local reference-data container.
    /// Set by `ConjugaApp.init()` so any view can bypass `@Environment(\.modelContext)`
    /// and hit the exact container used for seeding.
    @MainActor
    public static var localContainer: ModelContainer?

    /// The canonical model list for the local reference-data store.
    ///
    /// The main app AND the widget extension MUST build their `ModelContainer`
    /// from this exact set. Opening the store with a *subset* schema makes
    /// SwiftData destructively migrate it — silently dropping every table that
    /// isn't listed. That is how widget refreshes repeatedly wiped the bundled
    /// `Book`/`BookChapter` rows (and `TextbookChapter` before them). Keeping
    /// one shared list means a newly-added model can't be forgotten in the
    /// widget and quietly nuke its own data.
    public static var localSchemaModels: [any PersistentModel.Type] {
        [
            Verb.self, VerbForm.self, IrregularSpan.self,
            TenseGuide.self, CourseDeck.self, VocabCard.self,
            TextbookChapter.self, DownloadedVideo.self,
            Book.self, BookChapter.self,
            Lexeme.self,
        ]
    }
}
