package subscribeplanrepository

import (
	"fmt"
	"legalgo-BE-go/database"
	subscribedomain "legalgo-BE-go/internal/domain/subscribe"
	subscribeplandomain "legalgo-BE-go/internal/domain/subscribe_plan"
)

func (a *accessor) Delete(id string) error {
	var subsPlan database.SubscribePlan
	var basicPlan subscribeplandomain.SubscribePlan

	if err := a.db.First(&basicPlan, "code = ?", "basic").Error; err != nil {
		return fmt.Errorf("failed to find basic plan: %v", err)
	}

	if err := a.db.
		Model(&subscribedomain.Subscribe{}).
		Where("subscribe_plan_id = ?", id).
		Update("subscribe_plan_id", basicPlan.ID).Error; err != nil {
		return fmt.Errorf("failed to change subscribe plan: %v", err)
	}

	if err := a.db.Delete(&subsPlan, "id = ?", id).Error; err != nil {
		return fmt.Errorf("failed to delete subscribe plan %s : %v", id, err)
	}

	return nil
}
