//
//  XUserRole.swift
//  
//
//  Created by Michiel Carman on 1/31/24.
//

import Fluent
import Vapor
import Foundation
import FluentKit

final class mdlXUserRole: Model, Content {
    static let schema = "xUserRole"
    
    @ID(custom: "id", generatedBy: .database) var id: Int?
    @Parent(key: "userId") var user: mdlUser
    @Parent(key: "roleId") var role: mdlRole
    @Timestamp(key: "createDate", on: .create) var createdate: Date?
    @Field(key: "createUserId") var createuserid: Int?
    @Timestamp(key: "updateDate", on: .update) var updatedate: Date?
    @Field(key: "updateUserId") var updateuserid: Int?
    
    init(){}
    
    init(id: Int? = nil, userid: Int, roleid: Int, createdate: Date? = nil, createuserid: Int? = nil, updatedate: Date? = nil, updateuserid: Int? = nil) {
        self.id = id
        self.user.$id.value = userid
        self.role.$id.value = roleid
        self.createdate = createdate
        self.createuserid = createuserid
        self.updatedate = updatedate
        self.updateuserid = updateuserid
    }
    
}
extension mdlXUserRole{
    struct Create: AsyncMigration {
        func prepare(on database: Database) async throws {
            try await database.schema("xUserRole")
                .field("id", .int, .identifier(auto: true))
                .field("userId", .int, .references("user", "id"))
                .field("roleid", .int, .references("role", "id"))
                .field("createDate", .datetime)
                .field("createUserId", .int)
                .field("updateDate", .datetime)
                .field("updateUserId", .int)
                .create()
        }

        func revert(on database: Database) async throws {
            try await database.schema("user").delete()
        }
    }
    struct FixRoleId: AsyncMigration{
        func prepare(on database: Database) async throws{
            try await database.schema("xUserRole")
                .deleteField("roleid")
                .field("roleId", .int, .references("role", "id"))
                .update()
        }
        func revert(on database: Database) async throws {
            try await database.schema("xUserRole")
                .deleteField("roleId")
                .field("roleid", .int, .references("role", "id"))
                .update()
        }
    }
    public static func ObjQuery(req: Request) async throws -> QueryBuilder<mdlXUserRole>{
        
        let query = mdlXUserRole.query(on: req.db)
            .with(\.$user)
            .with(\.$role)
        
        if let x = req.parameters.get("x"){
            let decryptedString = try CustomCrypto.DecryptString(input: x)
            let array =  decryptedString.components(separatedBy: ":")
            ///This call is the standard get by id call
            if (array.count == 1){
                let id = Int(array[0])!
                return query.filter(\.$id == id)
            }
            ///Optional else if if there are multiple parameters in the call
            ///You must include an else for each call that has parameters
            ///Need to check the endpoint to get the right filter statements
            ///else if(x.count == 2){
            ///    let username = x[0]
            ///    let password = x[1]
            ///    return query.filter(\.$username == username).filter(\.$password == password)
            ///}
            else{
                throw Abort(.badRequest)
            }
            
        }
        else{
            return query
        }
    }
}




