package repository

import (
	"baron-sso-backend/internal/domain"
	"context"

	"gorm.io/gorm"
)

type RelyingPartyRepository interface {
	Create(ctx context.Context, rp *domain.RelyingParty) error
	Update(ctx context.Context, rp *domain.RelyingParty) error
	Delete(ctx context.Context, clientID string) error
	FindByID(ctx context.Context, clientID string) (*domain.RelyingParty, error)
	ListByTenantID(ctx context.Context, tenantID string) ([]domain.RelyingParty, error)
	ListAll(ctx context.Context) ([]domain.RelyingParty, error)
}

func (r *relyingPartyRepository) ListAll(ctx context.Context) ([]domain.RelyingParty, error) {
	var rps []domain.RelyingParty
	if err := r.db.WithContext(ctx).Find(&rps).Error; err != nil {
		return nil, err
	}
	return rps, nil
}

type relyingPartyRepository struct {
	db *gorm.DB
}

func NewRelyingPartyRepository(db *gorm.DB) RelyingPartyRepository {
	return &relyingPartyRepository{db: db}
}

func (r *relyingPartyRepository) Create(ctx context.Context, rp *domain.RelyingParty) error {
	return r.db.WithContext(ctx).Create(rp).Error
}

func (r *relyingPartyRepository) Update(ctx context.Context, rp *domain.RelyingParty) error {
	return r.db.WithContext(ctx).Save(rp).Error
}

func (r *relyingPartyRepository) Delete(ctx context.Context, clientID string) error {
	return r.db.WithContext(ctx).Delete(&domain.RelyingParty{}, "client_id = ?", clientID).Error
}

func (r *relyingPartyRepository) FindByID(ctx context.Context, clientID string) (*domain.RelyingParty, error) {
	var rp domain.RelyingParty
	if err := r.db.WithContext(ctx).First(&rp, "client_id = ?", clientID).Error; err != nil {
		return nil, err
	}
	return &rp, nil
}

func (r *relyingPartyRepository) ListByTenantID(ctx context.Context, tenantID string) ([]domain.RelyingParty, error) {
	var rps []domain.RelyingParty
	if err := r.db.WithContext(ctx).Where("tenant_id = ?", tenantID).Find(&rps).Error; err != nil {
		return nil, err
	}
	return rps, nil
}
