package kr.co.tobby48.medihand.controllers;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import kr.co.tobby48.medihand.models.Patient;
import kr.co.tobby48.medihand.models.User;
import kr.co.tobby48.medihand.payload.request.patient.AddPatientRequest;
import kr.co.tobby48.medihand.payload.request.patient.UpdatePatientRequest;
import kr.co.tobby48.medihand.repository.PatientRepository;
import kr.co.tobby48.medihand.repository.UserRepository;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/patient")
public class PatientController {
	@Autowired
	private PatientRepository patientRepository;

	@Autowired
	private UserRepository userRepository;
	
	
	
	@GetMapping("/{userId}")
	public List<Patient> getPatientByUsers(@PathVariable Long userId) {
		return patientRepository.findByUser_Id(userId);
	}
	
	@PostMapping("/")
	public ResponseEntity<?> save(@Valid @RequestBody AddPatientRequest request) {
		
		User user = userRepository.findById(request.getUser_id()).orElseGet(User::new);
		Patient patient = new Patient(request, user);
		patientRepository.save(patient);

//		return ResponseEntity.ok(new MessageResponse("User registered successfully!"));
		return ResponseEntity.ok(patient);
	}
	
	@PutMapping("/")
	public ResponseEntity<?> upate(@Valid @RequestBody UpdatePatientRequest request) {
		Patient patient = patientRepository.findById(request.getId()).orElseGet(Patient::new);
		patient = request.update(patient);
		patientRepository.save(patient);
		
		return ResponseEntity.ok(patient);
	}
	
	@DeleteMapping("/{id}")
	public ResponseEntity<?> delete(@PathVariable Long id) {
		patientRepository.deleteById(id);
		return ResponseEntity.ok(id);
	}
	
}
