package com.tasteby.controller;

import com.tasteby.domain.Memo;
import com.tasteby.security.AuthUtil;
import com.tasteby.service.MemoService;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class MemoController {

    private final MemoService memoService;

    public MemoController(MemoService memoService) {
        this.memoService = memoService;
    }

    @GetMapping("/restaurants/{restaurantId}/memo")
    public Memo getMemo(@PathVariable String restaurantId) {
        String userId = AuthUtil.getUserId();
        Memo memo = memoService.findByUserAndRestaurant(userId, restaurantId);
        if (memo == null) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "No memo");
        }
        return memo;
    }

    @PostMapping("/restaurants/{restaurantId}/memo")
    public Memo upsertMemo(@PathVariable String restaurantId,
                           @RequestBody Map<String, Object> body) {
        String userId = AuthUtil.getUserId();
        Double rating = body.get("rating") != null
                ? ((Number) body.get("rating")).doubleValue() : null;
        String text = (String) body.get("memo_text");
        LocalDate visitedAt = body.get("visited_at") != null
                ? LocalDate.parse((String) body.get("visited_at")) : null;
        return memoService.upsert(userId, restaurantId, rating, text, visitedAt);
    }

    @GetMapping("/users/me/memos")
    public List<Memo> myMemos() {
        return memoService.findByUser(AuthUtil.getUserId());
    }

    @DeleteMapping("/restaurants/{restaurantId}/memo")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void deleteMemo(@PathVariable String restaurantId) {
        String userId = AuthUtil.getUserId();
        if (!memoService.delete(userId, restaurantId)) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "No memo");
        }
    }
}
