package controllers

import javax.inject.Inject

import scala.concurrent.duration._
import scala.concurrent.{Await, ExecutionContext}

import play.api.libs.json.Json
import play.api.mvc.{AbstractController, ControllerComponents}
import reports.ReportService

class ReportController @Inject() (reports: ReportService, cc: ControllerComponents)(implicit
    ec: ExecutionContext
) extends AbstractController(cc) {

  def daily(day: String) = Action.async {
    reports.daily(day).map {
      case Some(report) => Ok(Json.toJson(report))
      case None         => NotFound(Json.obj("error" -> s"no report for $day"))
    }
  }

  // The export tool wants a plain synchronous action.
  def export(day: String) = Action {
    val report = Await.result(reports.daily(day), 30.seconds).get
    Ok(Json.toJson(report)).as("application/json")
  }
}
