//
//  cntrlCompartment.swift
//
//
//  Created by Michiel Carman on 4/5/2024.
//

import Fluent
import Vapor
import Crypto



struct cntrlCompartment: RouteCollection {
    func boot(routes: RoutesBuilder) throws {
        let rts = routes.grouped("compartments")
        rts.get(use: index)
        rts.get(":x", use: read)
        rts.post(use: create)
        rts.delete(":x", use: delete)
        //Additional routs added here
    }
    
    func index(req: Request) async throws -> Response {
        guard let obj = try? await mdlCompartment.ObjQuery(req: req).all() else {
            throw Abort(.badGateway, reason: "Something went wrong with this api.")
        }
        guard let response = try? await obj.encodeResponse(status: .ok, for: req) else{
            throw Abort(.noContent, reason: "Something went wrong decoding data.  Array could not be shown.")
        }
        return response
    }
    
    func read(req:Request) async throws -> Response{
        guard let obj = try? await mdlCompartment.ObjQuery(req: req).first() else{
            throw Abort(.notFound, reason: "Compartment was not found.")
        }
        guard let response = try? await obj.encodeResponse(status: .ok, for: req) else {
            throw Abort(.noContent, reason: "Something went wrong decoding object.")
        }
        return response
    }
    
    func create(req: Request) async throws -> Response {
        
        guard let obj = try? req.content.decode(mdlCompartment.self) else {
            throw Abort(.notAcceptable, reason: "Compartment json not formatted correctly or is missing parents.")
        }
        var exists = false
        if(obj.id != nil){
            obj._$idExists = true
            exists = true
        }
        guard let _ = try? await obj.save(on: req.db) else{
            throw Abort(.conflict, reason: "Something conflicts in the database. Compartment cannot be saved.")
        }
        
        guard let response = try? await obj.encodeResponse(status: exists ? .accepted : .created, for: req) else{
            throw Abort(.noContent, reason: "Something went wrong decoding data.  Compartment has been saved.")
        }
        return response
    }
    
    
    func delete(req: Request) async throws -> Response {
        guard let obj = try? await mdlCompartment.ObjQuery(req: req).first() else {
            throw Abort(.notFound, reason: "Compartment's ID was not supplied.  Compartment will not be deleted")
        }
        guard let _ = try? await obj.delete(on: req.db) else{
            throw Abort(.conflict, reason: "There was a conflict deleting Compartment.  Make sure it has not children.")
        }
        guard let response = try? await obj.encodeResponse(status: .ok, for: req) else{
            throw Abort(.noContent, reason: "Something went wrong decoding data.  Compartment has been deleted.")
        }
        return response
    }
}

