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

import Fluent
import Vapor
import Foundation
import FluentKit

final class mdlEquipment: Model, Content {
    static let schema = "equipment"
    
    @ID(custom: "id", generatedBy: .database) var id: Int?
    
    @Field(key: "number") var number: String?
    @Field(key: "isActive") var isactive: Bool?
    
    @OptionalParent(key: "customerId") var customer: mdlCustomer?
    @Parent(key: "modelId") var model: mdlModel
    @Parent(key: "equipmentTypeId") var equipmenttype: mdlEquipmentType
    @OptionalParent(key: "parentId") var parent: mdlEquipment?
    
    @Children(for: \.$equipment) var properties: [mdlObjProperty]
    @Children(for: \.$equipment) var templates: [mdlTemplate]
    @Siblings(through: mdlWorkOrderAttachment.self, from: \.$equipment, to: \.$workorder) 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, isactive: Bool? = nil, createuserid: Int? = nil, updateuserid: Int? = nil, customerid: Int? = nil, modelid: Int, equipmenttypeid: Int, parentid: Int? = nil) {
        self.id = id
        
        self.number = number
        self.isactive = isactive
        if(customerid != nil) { self.$customer.$id.value = customerid! }
        self.$model.$id.value = modelid
        self.$equipmenttype.$id.value = equipmenttypeid
        self.$parent.$id.value = parentid
        if(parentid != nil) { self.$parent.$id.value = parentid! }
        
        self.createuserid = createuserid
        self.updateuserid = updateuserid
    }
}

extension mdlEquipment{
    struct Create: AsyncMigration {
        func prepare(on database: Database) async throws {
            try await database.schema("equipment")
                .field("id", .int, .identifier(auto: true))
                .field("number", .string)
                .field("isActive", .bool)
                .field("customerId", .int, .references("customer", "id"))
                .field("modelId", .int, .references("model", "id"))
                .field("equipmentTypeId", .int, .references("equipmentType", "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("equipment").delete()
        }
    }
    struct AddParent: AsyncMigration {
        func prepare(on database: Database) async throws {
            try await database.schema("equipment")
                .field("parentId", .int, .references("equipment", "id"))
                .update()
        }

        func revert(on database: Database) async throws {
            try await database.schema("equipment")
                .deleteField("parentId")
                .update()
        }
    }
    public static func ObjQuery(req: Request) async throws -> QueryBuilder<mdlEquipment>{
        
        let query = mdlEquipment.query(on: req.db)
            .with(\.$customer)
            .with(\.$model)
            .with(\.$equipmenttype)
            .with(\.$parent)
            .with(\.$properties)
            .with(\.$templates)
            .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
            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
        }
    }
}



