package com.nursinghome.service;

import com.nursinghome.entity.Bill;
import com.nursinghome.entity.PaymentRecord;
import com.nursinghome.mapper.BillMapper;
import com.nursinghome.mapper.PaymentRecordMapper;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class BillService {
    private final BillMapper billMapper;
    private final PaymentRecordMapper paymentRecordMapper;

    public BillService(BillMapper billMapper, PaymentRecordMapper paymentRecordMapper) {
        this.billMapper = billMapper;
        this.paymentRecordMapper = paymentRecordMapper;
    }

    public Bill createBill(Bill bill) {
        if (bill.getTotal() == null) {
            bill.setTotal(calcTotal(bill));
        }
        if (bill.getStatus() == null) {
            bill.setStatus("UNPAID");
        }
        billMapper.insert(bill);
        return bill;
    }

    public BigDecimal calcTotal(Bill bill) {
        BigDecimal total = BigDecimal.ZERO;
        if (bill.getBedFee() != null) total = total.add(bill.getBedFee());
        if (bill.getCareFee() != null) total = total.add(bill.getCareFee());
        if (bill.getMealFee() != null) total = total.add(bill.getMealFee());
        if (bill.getOtherFee() != null) total = total.add(bill.getOtherFee());
        return total;
    }

    public List<Bill> listByElderId(Long elderId) {
        return billMapper.listByElderId(elderId);
    }

    public List<Bill> listByElderIds(List<Long> elderIds) {
        return billMapper.listByElderIds(elderIds);
    }

    public void payBill(Long billId, Long familyId, String method, BigDecimal amount) {
        Bill bill = new Bill();
        bill.setId(billId);
        bill.setStatus("PAID");
        bill.setPaidAt(LocalDateTime.now());
        billMapper.updateStatus(bill);

        PaymentRecord record = new PaymentRecord();
        record.setBillId(billId);
        record.setFamilyId(familyId);
        record.setAmount(amount);
        record.setMethod(method);
        record.setPaidAt(LocalDateTime.now());
        paymentRecordMapper.insert(record);
    }
}
