package repository

import (
	"context"
	"dataservices/commons/errs"
	"dataservices/internal/entity"
)

func SaveCustomDomain(ctx context.Context, domain *entity.CustomDomain) (*entity.CustomDomain, error) {
	err := MustFromContext(ctx).Table(entity.TableCustomDomain).Save(domain).Error
	if err != nil {
		return nil, errs.WrapGORMError(err, "failed to create custom_domain")
	}
	return domain, nil
}

func ListCustomDomainsByAppId(ctx context.Context, appId uint64) ([]*entity.CustomDomain, error) {
	var result []*entity.CustomDomain
	err := MustFromContext(ctx).Table(
		entity.TableCustomDomain,
	).Where(
		"dataapp_id=?",
		appId,
	).Find(&result).Error
	return result, err
}

func ListCustomDomainsByCustomDomainNameExceptExpired(ctx context.Context, customDomainName string) ([]*entity.CustomDomain, error) {
	var result []*entity.CustomDomain
	err := MustFromContext(ctx).Table(
		entity.TableCustomDomain,
	).Where(
		"custom_domain_name=? and expired=0",
		customDomainName,
	).Find(&result).Error
	return result, err
}

func GetCustomDomainById(ctx context.Context, appId, customDomainId uint64) (*entity.CustomDomain, error) {
	var result *entity.CustomDomain
	err := MustFromContext(ctx).Table(
		entity.TableCustomDomain,
	).Where(
		"id=? and dataapp_id=?",
		customDomainId,
		appId,
	).First(&result).Error
	return result, err
}

func DeleteCustomDomainById(ctx context.Context, customDomainId uint64) error {
	return MustFromContext(ctx).Table(
		entity.TableCustomDomain,
	).Where(
		"id=?",
		customDomainId,
	).Delete(&entity.CustomDomain{}).Error
}
