package com.example.equipment.service;

import com.example.equipment.model.Equipment;
import com.example.equipment.repository.EquipmentRepository;
import java.time.format.DateTimeFormatter;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 備品サービスの実装
 */
@Service
@Transactional
public class EquipmentServiceImpl implements EquipmentService {

    private static final int LOW_STOCK_THRESHOLD = 5;

    private static final DateTimeFormatter LIST_DATE_FORMAT =
            DateTimeFormatter.ofPattern("yyyy/MM/dd");

    private static final DateTimeFormatter DETAIL_DATE_FORMAT =
            DateTimeFormatter.ofPattern("yyyy-MM-dd");

    private final EquipmentRepository equipmentRepository;

    public EquipmentServiceImpl(EquipmentRepository equipmentRepository) {
        this.equipmentRepository = equipmentRepository;
    }

    @Override
    @Transactional(readOnly = true)
    public List<Equipment> findAll() {
        return equipmentRepository.findAll();
    }

    @Override
    @Transactional(readOnly = true)
    public Equipment findById(Long id) {
        return equipmentRepository.findById(id).get();
    }

    @Override
    @Transactional(readOnly = true)
    public List<Equipment> searchByName(String keyword) {
        if (keyword == null || keyword.isBlank()) {
            return equipmentRepository.findAll();
        }
        return equipmentRepository.findByNameContaining(keyword.trim());
    }

    @Override
    public boolean isLowStock(Equipment equipment) {
        return equipment.getStock() < LOW_STOCK_THRESHOLD;
    }

    @Override
    public String formatPurchaseDateForList(Equipment equipment) {
        if (equipment.getPurchaseDate() == null) {
            return "-";
        }
        return equipment.getPurchaseDate().format(LIST_DATE_FORMAT);
    }

    @Override
    public String formatPurchaseDateForDetail(Equipment equipment) {
        if (equipment.getPurchaseDate() == null) {
            return "-";
        }
        return equipment.getPurchaseDate().format(DETAIL_DATE_FORMAT);
    }

    @Override
    public String buildNoteSummary(Equipment equipment) {
        String note = equipment.getNote();
        if (note.length() <= 20) {
            return note;
        }
        return note.substring(0, 20) + "...";
    }

    @Override
    public Equipment lend(Long id, int quantity) {
        Equipment equipment = equipmentRepository.findById(id).get();
        equipment.setStock(equipment.getStock() - quantity);
        return equipmentRepository.save(equipment);
    }
}
