package com.healthcare.ohctech.service.impl;

import com.healthcare.ohctech.dto.FoodMasterDto;
import com.healthcare.ohctech.entity.FoodMaster;
import com.healthcare.ohctech.repository.FoodMasterRepo;
import com.healthcare.ohctech.service.FoodMasterService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
public class FoodMasterServiceImpl implements FoodMasterService {

    private final FoodMasterRepo foodMasterRepo;

    public FoodMasterServiceImpl(FoodMasterRepo foodMasterRepo) {
        this.foodMasterRepo = foodMasterRepo;
    }

    @Override
    public FoodMaster getFoodById(Long foodId) {
        return foodMasterRepo.findById(foodId)
                .orElseThrow(() -> new RuntimeException("Food not found for ID: " + foodId));
    }

    @Override
    public Page<FoodMaster> getAllFoods(Pageable pageable) {
        return foodMasterRepo.findAll(pageable);
    }

    @Override
    public void addFood(FoodMasterDto foodMasterDto) {
        FoodMaster foodMaster = new FoodMaster();
        mapDtoToEntity(foodMaster, foodMasterDto);
        foodMasterRepo.save(foodMaster);
    }

    @Override
    public void updateFood(FoodMasterDto foodMasterDto) {
        Long foodId = foodMasterDto.id();
        FoodMaster foodMaster = foodMasterRepo.findById(foodId)
                .orElseThrow(() -> new RuntimeException("Food not found for ID: " + foodId));

        mapDtoToEntity(foodMaster, foodMasterDto);
        foodMasterRepo.save(foodMaster);
    }

    @Override
    public void deleteFood(Long foodId) {
        FoodMaster foodMaster = foodMasterRepo.findById(foodId)
                .orElseThrow(() -> new RuntimeException("Food not found for ID: " + foodId));
        foodMasterRepo.delete(foodMaster);
    }

    private void mapDtoToEntity(FoodMaster foodMaster, FoodMasterDto foodMasterDto) {
        foodMaster.setFoodName(foodMasterDto.foodName());
    }
}