package com.expensetracker.api.expenses.controller;

import com.expensetracker.api.expenses.dto.CreateExpenseRequest;
import com.expensetracker.api.expenses.dto.ExpenseResponse;
import com.expensetracker.api.expenses.service.ExpenseService;
import jakarta.validation.Valid;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;

@RestController
@RequestMapping("/expenses")
public class ExpenseController {
  private final ExpenseService service;

  public ExpenseController(ExpenseService service) {
    this.service = service;
  }

  @PostMapping
  public ExpenseResponse create(@Valid @RequestBody CreateExpenseRequest req) {
    return service.create(req);
  }

  @GetMapping
  public Page<ExpenseResponse> list(
      @RequestParam(required = false) LocalDate from,
      @RequestParam(required = false) LocalDate to,
      @RequestParam(defaultValue = "0") int page,
      @RequestParam(defaultValue = "20") int size
  ) {
    return service.list(from, to, PageRequest.of(page, size));
  }

  @PutMapping("/{id}")
  public ExpenseResponse update(@PathVariable long id, @Valid @RequestBody CreateExpenseRequest req) {
    return service.update(id, req);
  }

  @DeleteMapping("/{id}")
  public void delete(@PathVariable long id) {
    service.delete(id);
  }
}
