package cn.novalon.gym.manage.member.repository;

import cn.novalon.gym.manage.member.entity.Member;
import cn.novalon.gym.manage.member.vo.MemberCardInfoVO;
import org.springframework.data.domain.Pageable;
import org.springframework.data.r2dbc.repository.Query;
import org.springframework.data.r2dbc.repository.R2dbcRepository;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 *  会员Repository
 *  @author 付嘉
 *  @date 2026-05-01
 */

@Repository
public interface IMemberRepository extends R2dbcRepository<Member, Long> {

    // UnionID查询会员
    Mono<Member> findByUnionId(String unionId);

    // 小程序OpenID查询会员
    Mono<Member> findByMiniappOpenId(String miniappOpenId);

    // 服务号OpenID查询会员
    Mono<Member> findByOfficialOpenId(String officialOpenId);

    // 手机号查询
    Mono<Member> findByPhone(String phone);

    /**
     * 分页查询所有会员
     */
    Flux<Member> findAllBy(Pageable pageable);

    /**
     * 查询会员的所有卡片
     */
    @Query("SELECT " +
            "   r.id, " +
            "   r.member_card_record_id, " +
            "   r.member_id, " +
            "   r.member_card_id, " +
            "   r.status, " +
            "   r.remaining_times, " +
            "   r.remaining_amount, " +
            "   r.expire_time, " +
            "   r.purchase_time, " +
            "   r.source_order_id, " +
            "   r.created_at, " +
            "   r.updated_at, " +
            "   r.version, " +
            "   r.card_composition, " +
            "   c.id AS card_id, " +
            "   c.member_card_id, " +
            "   c.member_card_name, " +
            "   c.member_card_type, " +
            "   c.member_card_price, " +
            "   c.member_card_validity_days, " +
            "   c.member_card_total_times, " +
            "   c.member_card_amount, " +
            "   c.member_card_status, " +
            "   c.extra_config, " +
            "   c.created_at AS card_created_at, " +
            "   c.updated_at AS card_updated_at " +
            "FROM member_card_record r " +
            "LEFT JOIN member_card c ON r.member_card_id = c.id " +
            "WHERE r.member_id = :memberId " +
            "AND r.deleted_at IS NULL " +
            "AND c.deleted_at IS NULL " +
            "ORDER BY r.created_at DESC")
    Flux<MemberCardInfoVO> findCardRecordsWithCardInfoByMemberId(Long memberId);
}
