import FluentSQLiteDriver
import FluentSQL
import Vapor

private extension FieldProperty {
    convenience init(_ key: User.Key) {
        self.init(key: key.key)
    }
}

private extension OptionalParentProperty {
    convenience init(_ key: User.Key) {
        self.init(key: key.key)
    }
}

/// A registered user
final class User: Model {

    enum Key: String {
        case id = "id"
        case name = "name"
        case hash = "hash"
        case points = "points"
        case table = "table_id"
        case recoveryEmail = "email"

        var key: FieldKey {
            .init(stringLiteral: rawValue)
        }
    }

    /// The name of the SQLite table
    static let schema = "user"

    /// The unique identifier for this user.
    @ID(key: .id)
    var id: UUID?

    /// The user's full name.
    @Field(.name)
    var name: String

    /// The hash of the user's password
    @Field(.hash)
    var passwordHash: String

    @Field(.recoveryEmail)
    var recoveryEmail: String?

    /// The user's total points
    @Field(.points)
    var points: Int

    /// The table to which this user currently belongs
    @OptionalParent(.table)
    var table: Table?

    /// The optional password reset request associated with this user
    @OptionalChild(for: \.$user)
    var resetRequest: PasswordReset?

    init() { }

    /// Creates a new user.
    init(id: UUID? = nil, name: String, hash: String, email: String? = nil) {
        self.id = id
        self.name = name
        self.passwordHash = hash
        self.points = 0
        self.recoveryEmail = email
    }
}
