package postgres

import (
	"context"
	"fmt"
)

type LoginIdentity struct {
	ID              string
	IdentityType    string
	Provider        string
	ProviderSubject string
	CountryCode     *string
	Mobile          *string
	Status          string
}

func (s *Store) ListIdentitiesByUserID(ctx context.Context, userID string) ([]LoginIdentity, error) {
	rows, err := s.pool.Query(ctx, `
		SELECT id, identity_type, provider, provider_subject, country_code, mobile, status
		FROM login_identities
		WHERE user_id = $1
		ORDER BY created_at ASC
	`, userID)
	if err != nil {
		return nil, fmt.Errorf("list identities by user id: %w", err)
	}
	defer rows.Close()

	var identities []LoginIdentity
	for rows.Next() {
		var identity LoginIdentity
		if err := rows.Scan(
			&identity.ID,
			&identity.IdentityType,
			&identity.Provider,
			&identity.ProviderSubject,
			&identity.CountryCode,
			&identity.Mobile,
			&identity.Status,
		); err != nil {
			return nil, fmt.Errorf("scan identity: %w", err)
		}
		identities = append(identities, identity)
	}
	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("iterate identities: %w", err)
	}
	return identities, nil
}
