//
//  Token.swift
//  
//
//  Created by Michiel Carman on 4/5/24.
//

import Vapor
import Fluent

enum SessionSource: Int, Content {
  case signup
  case login
}

final class Token: Model, Content{
    static let schema = "token"
    
    @ID(custom: "id", generatedBy: .database) var id: Int?
    @Parent(key: "userId") var user: mdlUser
    @Field(key: "value") var value: String
    @Field(key: "source") var source: SessionSource
    @Field(key: "expiresAt") var expiresat: Date?
    @Timestamp(key: "createdAt", on: .create) var createdat: Date?
    
    init(){}
    
    init(id: Int? = nil, userid: mdlUser.IDValue, token: String,
      source: SessionSource, expiresat: Date?) {
      self.id = id
      self.$user.id = userid
      self.value = token
      self.source = source
      self.expiresat = expiresat
    }
}
extension Token{
    struct Create: AsyncMigration {
      func prepare(on database: Database) async throws {
          try await database.schema(Token.schema)
          .field("id", .int, .identifier(auto: true))
          .field("userId", .int, .references("user", "id"))
          .field("value", .string, .required).unique(on: "value")
          .field("source", .int, .required)
          .field("createdAt", .datetime, .required)
          .field("expiresAt", .datetime)
          .create()
      }

      // 5
      func revert(on database: Database) async throws {
        try await database.schema(Token.schema).delete()
      }
    }
}
