//
//  mdlUser.swift
//
//
//  Created by Michiel Carman on 1/24/24.
//

import Fluent
import Vapor
import Foundation
import FluentKit

final class mdlUser: Model, Content {
    static let schema = "user"
    
    @ID(custom: "id", generatedBy: .database) var id: Int?
    
    @Field(key: "number") var number: String?
    @Field(key: "firstName") var firstname: String?
    @Field(key: "lastName") var lastname: String?
    @Field(key: "username") var username: String?
    @Field(key: "password") var password: String?
    @Field(key: "email") var email: String?
    @Field(key: "isActive") var isactive: Bool?
    
    @OptionalParent(key: "divisionId") var division: mdlDivision?
    @OptionalParent(key: "locationId") var location: mdlLocation?
    @OptionalParent(key: "gateId") var gate: mdlGate?
    
    @Siblings(through: mdlXUserRole.self, from: \.$user, to: \.$role) var roles: [mdlRole]
    
    @Children(for: \.$technician) var workorders: [mdlWorkOrder]
    
    @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, number: String? = nil, firstname: String? = nil, lastname: String? = nil, username: String? = nil, password: String? = nil, email: String? = nil, isactive: Bool? = nil, createuserid: Int? = nil, updateuserid: Int? = nil, divisionid: Int? = nil, locationid: Int? = nil, gateid: Int? = nil) {
        self.id = id
        
        self.number = number
        self.firstname = firstname
        self.lastname = lastname
        self.username = username
        self.password = password
        self.email = email
        self.isactive = isactive
        if(divisionid != nil) { self.$division.$id.value = divisionid } 
        if(locationid != nil) { self.$location.$id.value = locationid }
        if(gateid != nil) { self.$gate.$id.value = gateid }
        
        self.createuserid = createuserid
        self.updateuserid = updateuserid
    }
}

extension mdlUser{
    struct Create: AsyncMigration {
        func prepare(on database: Database) async throws {
            try await database.schema("user")
                .field("id", .int, .identifier(auto: true))
                .field("number", .string)
                .field("firstName", .string)
                .field("lastName", .string)
                .field("username", .string)
                .field("password", .string)
                .field("email", .string)
                .field("isActive", .bool)
                .field("divisionId", .int, .references("division", "id"))
                .field("locationId", .int, .references("location", "id"))
                .field("gateId", .int, .references("gate", "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()
        }
    }
    public static func ObjQuery(req: Request) async throws -> QueryBuilder<mdlUser>{
        
        let query = mdlUser.query(on: req.db)
            .with(\.$roles)
            .with(\.$division)
            .with(\.$location)
            .with(\.$gate)
            .with(\.$workorders)
        
        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
            
            let p = req.url.path.components(separatedBy: "/")[4]
            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(array.count == 2 && p.uppercased() == "LOGIN"){
                let username = array[0]
                let password = array[1]
                return query.filter(\.$username == username).filter(\.$password == password)
            }
            else{
                throw Abort(.badRequest, reason: "Parameter missmatch.")
            }
            
        }
        else{
            return query
        }
    }
}



