@testable import App
import Fluent
import XCTVapor

final class RoleTests: XCTestCase {
    func test1() async throws{
        let app = Application(.testing)
        defer{app.shutdown()}
        try await configure(app)
        let basepath = "/api/v2.0/roles/"
        let name = "testRole"
        let description = "Testing Role methods"
        let cuserid = -1
        let uuserid = -1
        //Insert object
        try app.test(.POST, basepath, beforeRequest: {
            req in
            let input = mdlRole(id: nil, name: name, description: description, createuserid: cuserid, updateuserid: uuserid)
            try req.content.encode(input)
        }, afterResponse: {
            res in
            XCTAssertEqual(res.status, .created)
            let obj = try res.content.decode(mdlRole.self)
            XCTAssertEqual(obj.name, name)
            let id = obj.id
            
            //Update object just created
            try app.test(.POST, basepath, beforeRequest:{
                req in
                let input = mdlRole(id: nil, name: name, description: "Test Update", createuserid: cuserid, updateuserid: uuserid)
            }, afterResponse: {
                res in
                XCTAssertEqual(res.status, .accepted)
                let obj = try res.content.decode(mdlRole.self)
                XCTAssertEqual(obj.name, name)
            })
            
            //Read all objects in the table
            try app.test(.GET, basepath, afterResponse: { res in
                XCTAssertEqual(res.status, .ok)
                XCTAssertEqual(res.headers.contentType, .json)
                _ = try res.content.decode([mdlRole].self)
            })
            
            //Read the object just inserted
            var parameter = try CustomCrypto.EncryptString(input: String(id!))
            
            var path = "\(basepath)\(parameter)"
            try app.test(.GET, path, afterResponse: { res in
                XCTAssertEqual(res.status, .ok)
                XCTAssertEqual(res.headers.contentType, .json)
                _ = try res.content.decode(mdlRole.self)
            })
            
            //Delete object just inserted
            let encryptedid = try CustomCrypto.EncryptString(input: String(id!))
            path = "api/v2.0/role/"
            let url = "\(path)\(encryptedid)"
            try app.test(.DELETE, url, afterResponse: {
                res in
                XCTAssertEqual(res.status, .ok)
                _ = try res.content.decode(mdlRole.self)
            })
        })
    }
}
