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


import Fluent
import Vapor
import Foundation
import FluentKit

final class mdlConsumption: Model, Content {
    static let schema = "consumption"
    
    @ID(custom: "id", generatedBy: .database) var id: Int?
    
    @Parent(key: "workOrderSegmentId") var segment: mdlWorkOrderSegment
    @Parent(key: "fluidId") var fluid: mdlFluid
    @Parent(key: "viscosityId") var viscosity: mdlViscosity
    
    @Field(key: "quantity") var quantity: Float?
    @Field(key: "sortOrder") var sortorder: Int?
    
    @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,
         segmentid: Int,
         fluidid: Int,
         viscosityid: Int,
         quantity: Float? = nil,
         sortorder: Int? = nil,
         createuserid: Int? = nil,
         updateuserid: Int? = nil
    ) {
        self.id = id
        self.$segment.$id.value = segmentid
        self.$fluid.$id.value = fluidid
        self.$viscosity.$id.value = viscosityid
        self.quantity = quantity
        self.sortorder = sortorder
        self.createuserid = createuserid
        self.updateuserid = updateuserid
    }
}
extension mdlConsumption{
    struct Create: AsyncMigration {
        func prepare(on database: Database) async throws {
            try await database.schema("consumption")
                .field("id", .int, .identifier(auto: true))
                .field("workOrderSegmentId", .int, .references("workOrderSegment", "id"))
                .field("fluid", .int, .references("fluid", "id"))
                .field("viscosity", .int, .references("viscosity", "id"))
                .field("quantity", .float)
                .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("consumption").delete()
        }
    }
    struct Mod1: AsyncMigration {
        func prepare(on database: Database) async throws {
            try await database.schema("consumption")
                .deleteField("fluid")
                .deleteField("viscosity")
                .field("fluidId", .int, .references("fluid", "id"))
                .field("viscosityId", .int, .references("viscosity", "id"))
                .update()
        }
        
        func revert(on database: Database) async throws {
            try await database.schema("consumption")
                .deleteField("fluidId")
                .deleteField("viscosityId")
                .field("fluid", .int, .references("fluid", "id"))
                .field("viscosity", .int, .references("viscosity", "id"))
                .update()
        }
    }
    public static func ObjQuery(req: Request) async throws -> QueryBuilder<mdlConsumption>{
        
        let query = mdlConsumption.query(on: req.db)
            .with(\.$segment)
            .with(\.$fluid)
            .with(\.$viscosity)
        
        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
        }
    }
}

