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


import Fluent
import Vapor
import Foundation
import FluentKit

final class mdlInspectionItemSpecItem: Model, Content {
    static let schema = "inspectionItemSpecItem"
    
    @ID(custom: "id", generatedBy: .database) var id: Int?
    @Parent(key: "inspectionItemSpecId") var inspectionitemspec: mdlInspectionItemSpec
    @Parent(key: "comparisonTypeId") var comparisontype: mdlComparisonType
    @Parent(key: "unitId") var unit: mdlUnit
    @Field(key: "name") var name: String?
    @Field(key: "average") var average: Float?
    @Field(key: "qualifier") var qualifier: String?
    @Field(key: "result") var result: String?
    @Field(key: "sortOrder") var sortorder: Int?
    
    @Children(for: \.$specitem) var tests: [mdlInspectionItemSpecItemTest]
    @Children(for: \.$specitem) var values: [mdlInspectionItemSpecItemValue]
    
    @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,
         inspectionitemspecid: Int,
         comparisontypeid: Int,
         unitid: Int,
         name: String? = nil,
         average: Float? = nil,
         qualifier: String? = nil,
         result: String? = nil,
         sortorder: Int? = 0,
         createuserid: Int? = -1,
         updateuserid: Int? = -1
    ) {
        self.id = id
        self.$inspectionitemspec.$id.value = inspectionitemspecid
        self.$comparisontype.$id.value = comparisontypeid
        self.$unit.$id.value = unitid
        self.name = name
        self.average = average
        self.qualifier = qualifier
        self.result = result
        self.sortorder = sortorder
        self.createuserid = createuserid
        self.updateuserid = updateuserid
    }
}
extension mdlInspectionItemSpecItem{
    struct Create: AsyncMigration {
        func prepare(on database: Database) async throws {
            try await database.schema("inspectionItemSpecItem")
                .field("id", .int, .identifier(auto: true))
                .field("inspectionItemSpecId", .int, .references("inspectionItemSpec", "id"))
                .field("comparisonTypeId", .int, .references("comparisonType", "id"))
                .field("unitId", .int, .references("unit", "id"))
                .field("name", .string)
                .field("average", .float)
                .field("qualifier", .string)
                .field("result", .string)
                .field("sortOrder", .int)
                .field("createDate", .datetime)
                .field("createUserId", .int)
                .field("updateDate", .datetime)
                .field("updateUserId", .int)
                .create()
        }
        
        func revert(on database: Database) async throws {
            try await database.schema("inspectionItemSpecItem").delete()
        }
    }
    public static func ObjQuery(req: Request) async throws -> QueryBuilder<mdlInspectionItemSpecItem>{
        
        let query = mdlInspectionItemSpecItem.query(on: req.db)
            .with(\.$inspectionitemspec)
            .with(\.$comparisontype)
            .with(\.$unit)
            .with(\.$tests)
            .with(\.$values)
        
        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
        }
    }
}

