package com.iisc.pods.bookservice.controller;

import com.iisc.pods.bookservice.exception.BookNotFoundException;
import com.iisc.pods.bookservice.model.Book;
import com.iisc.pods.bookservice.repository.BookRepository;
import org.apache.coyote.BadRequestException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
import java.util.UUID;


@RestController
@RequestMapping("/v1/api")
public class BookController {

    @Autowired
    private BookRepository bookRepository;

    @PostMapping(value = "/books", consumes = "application/json")
    public ResponseEntity<Book> createBook(@RequestBody Book book) {
        try {
            Book savedBook = bookRepository.save(book);
            return new ResponseEntity<>(savedBook, HttpStatus.CREATED);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PutMapping("/books/{id}")
    public ResponseEntity<Book> updateBook(@PathVariable String id, @RequestBody Book book) {
        try {
            // Ensure book ID matches request path variable
            if (!id.equals(book.getIsbn())) {
                throw new BadRequestException("Book ID in request body does not match path variable");
            }

            List<Book> existingBook = bookRepository.findByIsbn(id);
            if (existingBook.isEmpty()) {
                throw new BookNotFoundException(id);
            }


            Book updatedBook = bookRepository.save(book);
            return new ResponseEntity<>(updatedBook, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @DeleteMapping("/books/{id}")
    public ResponseEntity<Void> deleteBook(@PathVariable String id) {
     try {
            if (bookRepository.findByIsbn(id) == null) {
                throw new BookNotFoundException(id);
            }
            bookRepository.deleteByIsbn(id);
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/books")
    public ResponseEntity<?> searchBooks(
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "isbn", required = false) String isbn,
            @RequestParam(value = "author", required = false) String author) {
      try {
          // Handle empty search criteria
          if (name == null && isbn == null && author == null) {
              return ResponseEntity.badRequest().body("Please provide at least one search criteria: name, isbn, or author");
          }

          // Perform search based on provided criteria
          List<Book> foundBooks;
          if (name != null && isbn != null && author != null) {
              foundBooks = bookRepository.findByNameContainingAndIsbnAndAuthor(name, isbn, author);
          } else if (name != null && author != null) {
              foundBooks = bookRepository.findByNameContainingAndAuthor(name, author);
          } else if (isbn != null && author != null) {
              foundBooks = bookRepository.findByIsbnAndAuthor(isbn, author);
          } else if (name != null) {
              foundBooks = bookRepository.findByNameContaining(name);
          } else if (isbn != null) {
              foundBooks = bookRepository.findByIsbn(isbn);
          } else {
              foundBooks = bookRepository.findByAuthor(author);
          }

          return ResponseEntity.ok(foundBooks);
      }catch (Exception e) {
          // Log the exception for debugging
          System.out.println("Error occurred during book search:"+e);

          // Return a generic error response to the user
          return ResponseEntity.internalServerError().body("An error occurred while processing the request");
      }
    }


}
