import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
import type CompanyReviewModuleService from "../../../../../modules/company-review/service"
import { COMPANY_REVIEW_MODULE } from "../../../../../modules/company-review"

export async function POST(req: MedusaRequest, res: MedusaResponse) {
  const { id } = req.params
  const body = req.body as {
    author_name?: string
    rating?: number
    body?: string
    is_published?: boolean
  }

  const data: Record<string, unknown> = {}

  if (typeof body.author_name === "string" && body.author_name.trim()) {
    data.author_name = body.author_name.trim()
  }

  if (body.rating !== undefined) {
    const rating = Number(body.rating)
    if (!Number.isInteger(rating) || rating < 1 || rating > 5) {
      return res.status(400).json({ message: "La note doit etre un entier entre 1 et 5." })
    }
    data.rating = rating
  }

  if (typeof body.body === "string" && body.body.trim()) {
    data.body = body.body.trim()
  }

  if (typeof body.is_published === "boolean") {
    data.is_published = body.is_published
  }

  const companyReviewModuleService = req.scope.resolve<CompanyReviewModuleService>(COMPANY_REVIEW_MODULE)
  const updatedReview = await companyReviewModuleService.updateCompanyReviews({ id, ...data })

  res.json({ review: updatedReview })
}

export async function DELETE(req: MedusaRequest, res: MedusaResponse) {
  const { id } = req.params
  const companyReviewModuleService = req.scope.resolve<CompanyReviewModuleService>(COMPANY_REVIEW_MODULE)
  await companyReviewModuleService.deleteCompanyReviews([id])

  res.json({ id, deleted: true })
}
