package postgres

import (
	"context"

	"github.com/break/junhong_cmp_fiber/internal/model"
	"gorm.io/gorm"
)

// PersonalCustomerOpenIDStore 个人客户 OpenID 关联数据访问层
type PersonalCustomerOpenIDStore struct {
	db *gorm.DB
}

// NewPersonalCustomerOpenIDStore 创建个人客户 OpenID Store
func NewPersonalCustomerOpenIDStore(db *gorm.DB) *PersonalCustomerOpenIDStore {
	return &PersonalCustomerOpenIDStore{db: db}
}

// FindByAppIDAndOpenID 根据 AppID 和 OpenID 查询关联记录
func (s *PersonalCustomerOpenIDStore) FindByAppIDAndOpenID(ctx context.Context, appID, openID string) (*model.PersonalCustomerOpenID, error) {
	var record model.PersonalCustomerOpenID
	if err := s.db.WithContext(ctx).
		Where("app_id = ? AND open_id = ?", appID, openID).
		First(&record).Error; err != nil {
		return nil, err
	}
	return &record, nil
}

// FindByUnionID 根据 UnionID 查询首条关联记录
func (s *PersonalCustomerOpenIDStore) FindByUnionID(ctx context.Context, unionID string) (*model.PersonalCustomerOpenID, error) {
	var record model.PersonalCustomerOpenID
	if err := s.db.WithContext(ctx).
		Where("union_id = ?", unionID).
		Order("id ASC").
		First(&record).Error; err != nil {
		return nil, err
	}
	return &record, nil
}

// Create 创建 OpenID 关联记录
func (s *PersonalCustomerOpenIDStore) Create(ctx context.Context, record *model.PersonalCustomerOpenID) error {
	return s.db.WithContext(ctx).Create(record).Error
}

// ListByCustomerID 根据客户 ID 查询所有 OpenID 关联记录
func (s *PersonalCustomerOpenIDStore) ListByCustomerID(ctx context.Context, customerID uint) ([]*model.PersonalCustomerOpenID, error) {
	var records []*model.PersonalCustomerOpenID
	if err := s.db.WithContext(ctx).
		Where("customer_id = ?", customerID).
		Order("id ASC").
		Find(&records).Error; err != nil {
		return nil, err
	}
	return records, nil
}
