// Step 1: Import the apiPost function from the database module
import { apiPost } from '../../database'

// Step 2: Define an async function to handle POST requests for deleting a movie
export async function POST(req: Request, res: Response) {
  // Step 3: Parse the request body as JSON
  const content = await req.json()

  // Step 4: Define the required properties for the movie deletion
  const requiredProperties = ['userId', 'slug']

  // Step 5: Check for missing required properties
  const missingProperty = requiredProperties.find(
    (property) => !(property in content)
  )

  // Step 6: Return an error response if a required property is missing
  if (missingProperty) {
    return Response.json(
      {
        error: `Missing required property: ${missingProperty}`,
      },
      {
        status: 400,
        headers: { 'content-type': 'application/json' },
      }
    )
  }

  // Step 7: Extract the userId and slug from the request body
  const { userId, slug } = content

  // Step 8: Define the SQL query to delete the movie
  const query = `DELETE FROM movies WHERE slug = ? AND userId = ?`

  // Step 9: Define the values to be used in the SQL query
  const values = [slug, userId]

  // Step 10: Initialize variables to store the response status and body
  let status, body

  // Step 11: Execute the SQL query using the apiPost function
  await apiPost(query, values)
    .then(() => {
      // Step 12: Set the response status and body on success
      status = 200
      body = { message: 'Successfully deleted movie' }
    })
    .catch((err) => {
      // Step 13: Set the response status and body on error
      status = 400
      body = err
    })

  // Step 14: Return the response as JSON
  return Response.json(body, {
    status,
    headers: { 'content-type': 'application/json' },
  })
}