package com.example.todo;

import java.net.URI;
import java.util.List;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/todos")
public class PersonalTodoController {
    private final PersonalTodoService service;
    public PersonalTodoController(PersonalTodoService service) { this.service=service; }
    @GetMapping public List<PersonalTodo> list(@AuthenticationPrincipal Jwt jwt) {
        return service.list(jwt.getSubject());
    }
    @GetMapping("/{id}") public PersonalTodo get(@PathVariable String id,@AuthenticationPrincipal Jwt jwt) {
        return service.get(id,jwt.getSubject());
    }
    @PostMapping public ResponseEntity<PersonalTodo> create(@AuthenticationPrincipal Jwt jwt,
        @Valid @RequestBody TodoRequest request) {
        PersonalTodo todo=service.create(jwt.getSubject(),request);
        return ResponseEntity.created(URI.create("/api/todos/"+todo.getId())).body(todo);
    }
    @PutMapping("/{id}") public PersonalTodo update(@PathVariable String id,
        @AuthenticationPrincipal Jwt jwt,@Valid @RequestBody TodoRequest request) {
        return service.update(id,jwt.getSubject(),request);
    }
    @DeleteMapping("/{id}") public ResponseEntity<Void> delete(@PathVariable String id,
        @AuthenticationPrincipal Jwt jwt) {
        service.delete(id,jwt.getSubject()); return ResponseEntity.noContent().build();
    }
}
