package com.example.demo.controller;

import java.security.Principal;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.ModelAttribute;

import com.example.demo.dto.ProfileDto;
import com.example.demo.dto.UpdateProfileDto;
import com.example.demo.service.UserService;

@Controller
public class ProfileController {

	private final UserService userService;

	public ProfileController(UserService userService) {
		this.userService = userService;
	}

	@GetMapping("/users/{id}")
	public String viewPublicProfile(@PathVariable Integer id, Model model, Principal principal) {
		ProfileDto profile = userService.getProfileByUserId(id);
		model.addAttribute("profile", profile);
		model.addAttribute("guest", principal == null);
		return "public-profile";
	}

	@GetMapping("/my-profile")
	public String viewMyProfile(Principal principal, Model model) {
		String username = principal.getName();

		ProfileDto profile = userService.getCurrentUserProfile(username);

		UpdateProfileDto updateProfileDto = new UpdateProfileDto();
		updateProfileDto.setDisplayName(profile.getDisplayName());
		updateProfileDto.setBio(profile.getBio());

		model.addAttribute("profile", profile);
		model.addAttribute("updateProfileDto", updateProfileDto);
		model.addAttribute("guest", false);

		return "my-profile";
	}

	@PostMapping("/my-profile/update")
	public String updateMyProfile(@ModelAttribute UpdateProfileDto dto, Principal principal) {
		String username = principal.getName();
		userService.updateProfile(username, dto);
		return "redirect:/my-profile";
	}
}