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

import Fluent
import Vapor
import Foundation
import FluentKit

final class mdlItem: Model, Content {
    static let schema = "item"
    
    @ID(custom: "id", generatedBy: .database) var id: Int?
    
    @Field(key: "name") var name: String?
    @Field(key: "description") var description: String?
    @Field(key: "isActive") var isactive: Bool?
    
    @Parent(key: "categoryId") var category: mdlCategory
    @OptionalParent(key: "smscCodeId") var smsccode: mdlSMSCCode?
    @Parent(key: "inputTypeId") var inputtype: mdlInputType
    
    @Children(for: \.$item) var templateitems: [mdlTemplateItemSpec]
    
    @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, name: String? = nil, description: String? = nil, isactive: Bool? = true, createuserid: Int? = nil, updateuserid: Int? = nil, categoryid: Int, smsccodeid: Int? = nil, inputtypeid: Int) {
        self.id = id
        
        self.name = name
        self.description = description
        self.isactive = isactive
        self.$category.$id.value = categoryid
        if(smsccodeid != nil){ self.$smsccode.$id.value = smsccodeid }
        self.$inputtype.$id.value = inputtypeid
        
        self.createuserid = createuserid
        self.updateuserid = updateuserid
    }
}

extension mdlItem{
    struct Create: AsyncMigration {
        func prepare(on database: Database) async throws {
            try await database.schema("item")
                .field("id", .int, .identifier(auto: true))
                .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("item").delete()
        }
    }
    struct Mod1: AsyncMigration {
        func prepare(on database: Database) async throws {
            try await database.schema("item")
                .field("categoryId", .int, .references("category", "id"))
                .field("smscCodeId", .int, .references("smscCode", "id"))
                .field("inputTypeId", .int, .references("inputType", "id"))
                .update()
        }

        func revert(on database: Database) async throws {
            try await database.schema("item")
                .deleteField("categoryId")
                .deleteField("smscCodeId")
                .deleteField("inputTypeId")
                .update()
        }
    }
    public static func ObjQuery(req: Request) async throws -> QueryBuilder<mdlItem>{
        
        let query = mdlItem.query(on: req.db)
            .with(\.$templateitems)
        
        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
        }
    }
}



