package com.nursinghome.service;

import com.nursinghome.common.ApiException;
import com.nursinghome.entity.Elder;
import com.nursinghome.entity.FamilyElder;
import com.nursinghome.entity.User;
import com.nursinghome.mapper.FamilyElderMapper;
import com.nursinghome.util.PasswordUtil;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class FamilyService {
    private final UserService userService;
    private final ElderService elderService;
    private final FamilyElderMapper familyElderMapper;

    public FamilyService(UserService userService, ElderService elderService, FamilyElderMapper familyElderMapper) {
        this.userService = userService;
        this.elderService = elderService;
        this.familyElderMapper = familyElderMapper;
    }

    public User registerFamily(String username, String password, String name, String phone, String elderIdCard, String relationship) {
        Elder elder = elderService.findByIdCard(elderIdCard);
        if (elder == null) {
            throw new ApiException("未找到该亲属");
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setName(name);
        user.setPhone(phone);
        user.setRole("FAMILY");
        user.setStatus(1);
        userService.createUser(user, true);

        FamilyElder relation = new FamilyElder();
        relation.setFamilyId(user.getId());
        relation.setElderId(elder.getId());
        relation.setRelationship(relationship);
        familyElderMapper.insert(relation);
        return user;
    }

    public List<FamilyElder> listRelations(Long familyId) {
        return familyElderMapper.listByFamilyId(familyId);
    }
}
