package com.sourcefellows.patterns.stateless;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import java.util.List;

@RestController
@RequestMapping("/api/todos")
public class TodoController {

    @Autowired
    private TodoService todoService;

    // GET: Retrieve all tasks
    @GetMapping
    public ResponseEntity<List<Todo>> getAllTodos(@RequestHeader("Authorization") String token) {
        validateToken(token); // JWT-Validierung
        return ResponseEntity.ok(todoService.getAllTodos());
    }

    // POST: Create a new task
    @PostMapping
    public ResponseEntity<Todo> createTodo(@RequestBody Todo todo,
                                           @RequestHeader("Authorization") String token) {
        validateToken(token); // JWT-Validierung
        Todo createdTodo = todoService.createTodo(todo);
        return ResponseEntity.status(HttpStatus.CREATED).body(createdTodo);
    }

    // DELETE: Delete a task by ID
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteTodo(@PathVariable("id") Long id, @RequestHeader("Authorization") String token) {
        validateToken(token); // JWT-Validierung
        todoService.deleteTodoById(id);
        return ResponseEntity.noContent().build();
    }

    // Helper: Validate JWT Token (Mocked)
    private void validateToken(String token) {
        if (token == null || !token.startsWith("Bearer ")) {
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid Token");
        }
        // Optional: Decode and validate JWT logic
    }
}
