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


import Fluent
import Vapor
import Foundation
import FluentKit

final class mdlInspectionItem: Model, Content {
    static let schema = "inspectionItem"
    
    @ID(custom: "id", generatedBy: .database) var id: Int?
    
    @Parent(key: "inspectionCategoryId") var category: mdlInspectionCategory
    @Parent(key: "inputTypeId") var inputtype: mdlInputType
    @OptionalParent(key: "smscCodeId") var smsccode: mdlSMSCCode?
    @Field(key: "name") var name: String?
    @Field(key: "description") var description: String?
    @Field(key: "sortOrder") var sortorder: Int?
    @OptionalParent(key: "previousInspectionItemId") var previousinspectionitem: mdlInspectionItem?
    @OptionalParent(key: "previousInspectionItemResponseId") var previousinspectionitemresponse: mdlInspectionItemResponse?
    
    @Children(for: \.$inspectionitem) var responses: [mdlInspectionItemResponse]
    @Children(for: \.$inspectionitem) var specs: [mdlInspectionItemSpec]
    @Children(for: \.$item) var notes: [mdlNote]
    
    @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,
         inspectioncategoryid: Int,
         inputtypeid: Int,
         smsccodeid: Int? = nil,
         name: String? = nil,
         description: String? = nil,
         sortorder: Int? = 0,
         previousinspectionitemid: Int? = nil,
         previousinspectionitemresponseid: Int? = nil,
         createuserid: Int? = nil,
         updateuserid: Int? = nil
    ) {
        self.id = id
        self.$category.$id.value = inspectioncategoryid
        self.$inputtype.$id.value = inputtypeid
        self.name = name
        self.description = description
        self.sortorder = sortorder
        if(previousinspectionitemid != nil){self.$previousinspectionitem.$id.value = previousinspectionitemid}
        if(previousinspectionitemresponseid != nil){self.$previousinspectionitemresponse.$id.value = previousinspectionitemresponseid}
        self.createuserid = createuserid
        self.updateuserid = updateuserid
    }
}
extension mdlInspectionItem{
    struct Create: AsyncMigration {
        func prepare(on database: Database) async throws {
            try await database.schema("inspectionItem")
                .field("id", .int, .identifier(auto: true))
                .field("inspectionCategoryId", .int, .references("inspectionCategory", "id"))
                .field("inputTypeId", .int, .references("inputType", "id"))
                .field("name", .string)
                .field("description", .string)
                .field("sortOrder", .int)
                .field("previousInspectionItemId", .int, .references("inspectionItem", "id"))
                //.field("previousInspectionItemResponsId", .int, .references("inspectionItemResponse", "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("inspectionItem").delete()
        }
    }
    struct Mod1: AsyncMigration {
        func prepare(on database: Database) async throws {
            try await database.schema("inspectionItem")
                .field("previousInspectionItemResponseId", .int, .references("inspectionItemResponse", "id"))
                .update()
        }
        
        func revert(on database: Database) async throws {
            try await database.schema("inspectionItem")
                .deleteField("previousInspectionItemResponsId")
                .update()
        }
    }
    struct Mod2: AsyncMigration {
        func prepare(on database: Database) async throws {
            try await database.schema("inspectionItem")
                .field("smscCodeId", .int, .references("smscCode", "id"))
                .update()
        }
        
        func revert(on database: Database) async throws {
            try await database.schema("inspectionItem")
                .deleteField("previousInspectionItemResponsId")
                .update()
        }
    }
    public static func ObjQuery(req: Request) async throws -> QueryBuilder<mdlInspectionItem>{
        
        let query = mdlInspectionItem.query(on: req.db)
            .with(\.$category)
            .with(\.$inputtype)
            .with(\.$smsccode)
            .with(\.$previousinspectionitem)
            .with(\.$previousinspectionitemresponse)
            .with(\.$responses)
            .with(\.$specs)
            .with(\.$notes)
        
        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
        }
    }
}

