import FluentKit import HummingbirdFluent /// Reads and creates accounts through the default database. public struct AccountRepository: Sendable { // MARK: Constants /// The email of the demo buyer the prototype's stubbed passkey signs in. public static let demoEmail = Seed.accounts[0].email // MARK: Properties private let fluent: Fluent // MARK: Initializers /// Creates a repository backed by the given `Fluent` service. /// - Parameter fluent: the service whose default database the repository operates on. public init( fluent: Fluent ) { self.fluent = fluent } // MARK: Methods /// Fetches the account with the given email, creating it when there is none: one step both signs in and joins. /// /// A new account is named after the email's local part until its owner picks a display name. /// - Parameter email: the account's normalized email address. /// - Returns: the account, existing or new. public func account( email: String ) async throws -> User { if let record = try await UserRecord.query(on: fluent.db()) .filter(\.$email == email) .first() { return try record.snapshot } let record = UserRecord( email: email, displayName: String(email.prefix { $0 != "@" }) ) try await record.save(on: fluent.db()) return try record.snapshot } }