Copy of Snippet "New Snippet"

package com.examly.springapp.controller;

import com.examly.springapp.model.Movie;
import com.examly.springapp.service.MovieService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/movies")
public class MovieController {

@Autowired
private MovieService movieService;

@GetMapping
public ResponseEntity<Page<Movie>> getMovies(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size,
@RequestParam(defaultValue = "title,asc") String sort) {

String sortParams = sort.split(",");
Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.fromString(sortParams[1]), sortParams[0]));

Page<Movie> movies = movieService.getMovies(pageable);
return ResponseEntity.ok(movies);
}

@GetMapping("/{id}")
public ResponseEntity<Movie> getMovieById(@PathVariable int id) {
Optional<Movie> movie = movieService.getMovieById(id);
return movie.map(ResponseEntity::ok)
.orElse(ResponseEntity.status(HttpStatus.NOT_FOUND).build());
}

@PostMapping
public ResponseEntity<Movie> createMovie(@RequestBody Movie movie) {
Movie createdMovie = movieService.createMovie(movie);
return ResponseEntity.status(HttpStatus.CREATED).body(createdMovie);
}

@PutMapping("/{id}")
public ResponseEntity<Movie> updateMovie(@PathVariable int id, @RequestBody Movie movie) {
Movie updatedMovie = movieService.updateMovie(id, movie);
if (updatedMovie != null) {
return ResponseEntity.ok(updatedMovie);
}
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}

@DeleteMapping("/{id}")
public ResponseEntity<Boolean> deleteMovie(@PathVariable int id) {
boolean isDeleted = movieService.deleteMovie(id);
if (isDeleted) {
return ResponseEntity.ok(true);
}
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(false);
}
}