import express from "express";
import {Any, JsonObject, JsonProperty} from "json2typescript";
import parser from "./parser";

@JsonObject('Response')
export class Response<Result = unknown> {

  @JsonProperty('status', Number)
  status: number = undefined;

  @JsonProperty('message', String)
  message: string = undefined;

  @JsonProperty('result', Any, true)
  result: Result = undefined;

  @JsonProperty('error', String, true)
  error: string = undefined;

  public static buildSuccess<Result = unknown>(message: string, result?: Result): Response<Result> {
    const inst = new Response<Result>();
    inst.status = 200;
    inst.message = message;
    inst.result = result;
    return inst;
  }

  public static buildError(message: string, error?: string, status = 500): Response {
    const inst = new Response();
    inst.status = status;
    inst.message = message;
    inst.error = error;
    return inst;
  }

  public send(res: express.Response) {
    console.log('sending shite', this.result);
    res.status(this.status).json(parser.serializeObject(this));
  }

}
