//
//  mdlTemplate.swift
//
//
//  Created by Michiel Carman on 2/16/24.
//


import Fluent
import Vapor
import Foundation
import FluentKit

final class mdlTemplate: Model, Content {
    static let schema = "template"
    
    @ID(custom: "id", generatedBy: .database) var id: Int?
    
    @OptionalParent(key: "inspectionLevelId") var level: mdlInspectionLevel?
    @OptionalParent(key: "productId") var product: mdlProduct?
    @OptionalParent(key: "makeId") var make: mdlMake?
    @OptionalParent(key: "modelId") var model: mdlModel?
    @OptionalParent(key: "customerId") var customer: mdlCustomer?
    @OptionalParent(key: "equipmentId") var equipment: mdlEquipment?
    
    @Children(for: \.$template) var categories: [mdlTemplateCategory]
    
    @Field(key: "name") var name: String?
    @Field(key: "description") var description: String?
    @Field(key: "isActive") var isactive: Bool?
    
    @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,
         levelid: Int? = nil,
         productid: Int? = nil,
         makeid: Int? = nil,
         modelid: Int? = nil,
         customerid: Int? = nil,
         equipmentid: Int? = nil,
         name: String? = nil,
         description: String? = nil,
         isactive: Bool? = true,
         createuserid: Int? = nil,
         updateuserid: Int? = nil
    ) {
        self.id = id
        if(levelid != nil) {self.$level.$id.value = levelid}
        if(productid != nil){self.$product.$id.value = productid}
        if(makeid != nil){self.$make.$id.value = makeid}
        if(modelid != nil){self.$model.$id.value = modelid}
        if(customerid != nil){self.$customer.$id.value = customerid}
        if(equipmentid != nil){self.$equipment.$id.value = equipmentid}
        self.name = name
        self.description = description
        self.isactive = isactive
        self.createuserid = createuserid
        self.updateuserid = updateuserid
    }
}
extension mdlTemplate{
    struct Create: AsyncMigration {
        func prepare(on database: Database) async throws {
            try await database.schema("template")
                .field("id", .int, .identifier(auto: true))
                .field("inspectionLevelId", .int, .references("inspectionLevel", "id"))
                .field("productId", .int, .references("product", "id"))
                .field("makeId", .int, .references("make", "id"))
                .field("modelId", .int, .references("model", "id"))
                .field("customerId", .int, .references("customer", "id"))
                .field("equipment", .int, .references("equipment", "id"))
                .field("name", .string)
                .field("description", .string)
                .field("isActive", .bool)
                .field("createDate", .datetime)
                .field("createUserId", .int)
                .field("updateDate", .datetime)
                .field("updateUserId", .int)
                .create()
        }
        
        func revert(on database: Database) async throws {
            try await database.schema("template").delete()
        }
    }
    struct Mod1: AsyncMigration {
        func prepare(on database: Database) async throws {
            try await database.schema("template")
                .deleteField("equipment")
                .field("equipmentId", .int, .references("equipment", "id"))
                .update()
        }
        
        func revert(on database: Database) async throws {
            try await database.schema("template")
                .deleteField("equipmentId")
                .field("equipment", .int, .references("equipment", "id"))
                .update()
        }
    }
    public static func ObjQuery(req: Request) async throws -> QueryBuilder<mdlTemplate>{
        
        let query = mdlTemplate.query(on: req.db)
            .with(\.$level)
            .with(\.$product)
            .with(\.$make)
            .with(\.$model)
            .with(\.$customer)
            .with(\.$equipment)
            .with(\.$categories)
        
        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
        }
    }
}

