package org.initialde.yakasave.Api;

import jakarta.validation.constraints.Min;
import org.initialde.yakasave.Application.ContributeToSavingsFund;
import org.initialde.yakasave.Domain.Entities.SavingsFund;
import org.initialde.yakasave.Domain.Exceptions.NotExistsSavingsFundException;
import org.initialde.yakasave.Infrastructure.Persistence.SavingsFundRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/savings-fund")
public class ContributeToSavingsFundController {
    private final SavingsFundRepository savingsFundRepository;
    private final ContributeToSavingsFund contributeToSavingsFund;

    @Autowired
    public ContributeToSavingsFundController(SavingsFundRepository savingsFundRepository,
                                             ContributeToSavingsFund contributeToSavingsFund) {
        this.savingsFundRepository = savingsFundRepository;
        this.contributeToSavingsFund = contributeToSavingsFund;
    }
    @PatchMapping("/{reference}/contribute")
    public void depositMoneyIntoSavingsFund(@PathVariable String reference, @RequestBody @Min(100) double amount) {
        Optional<SavingsFund> savingsFundOpt = savingsFundRepository.findByReference(reference);

        if (savingsFundOpt.isEmpty()) {
            throw new NotExistsSavingsFundException();
        }
        var savingsFund = savingsFundOpt.get();
        contributeToSavingsFund.contribute(savingsFund, amount);
    }
}
