package system

import (
	"context"
	"kra/internal/biz/system"

	"gorm.io/gorm"
)

func (r *apiRepo) IgnoredAPIs(ctx context.Context) ([]*system.API, error) {
	var pos []ignoredAPIPO
	if err := r.data.DB().WithContext(ctx).Find(&pos).Error; err != nil {
		return nil, err
	}
	out := make([]*system.API, 0, len(pos))
	for _, po := range pos {
		out = append(out, &system.API{Path: po.Path, Method: po.Method})
	}
	return out, nil
}
func (r *apiRepo) SetAPIIgnored(ctx context.Context, path, method string, ignored bool) error {
	po := ignoredAPIPO{Path: path, Method: method}
	if ignored {
		// The compatible endpoint creates an ignore row on every request (the table has no
		// path/method uniqueness constraint); retain that observable behavior.
		return r.data.DB().WithContext(ctx).Create(&po).Error
	}
	return r.data.DB().WithContext(ctx).Unscoped().Where("path = ? AND method = ?", po.Path, po.Method).Delete(&ignoredAPIPO{}).Error
}
func (r *apiRepo) ApplyAPISync(ctx context.Context, added, deleted []*system.API) error {
	return r.data.DB().WithContext(ctx).Transaction(func(tx *gorm.DB) error {
		if len(added) > 0 {
			pos := make([]apiPO, 0, len(added))
			for _, item := range added {
				pos = append(pos, apiPO{Path: item.Path, Method: item.Method, Description: item.Description, APIGroup: item.APIGroup})
			}
			// Insert the submitted newApis slice as-is. Do not silently
			// collapse repeated/existing path+method pairs here; sys_apis itself
			// intentionally has no uniqueness constraint.
			if err := tx.Create(&pos).Error; err != nil {
				return err
			}
		}
		for _, item := range deleted {
			var ids []uint
			if err := tx.Model(&apiPO{}).Where("path = ? AND method = ?", item.Path, item.Method).Pluck("id", &ids).Error; err != nil {
				return err
			}
			if len(ids) > 0 {
				if err := deletePoliciesForPath(tx, item.Path, item.Method); err != nil {
					return err
				}
				if err := tx.Where("api_id IN ?", ids).Delete(&authorityAPIPO{}).Error; err != nil {
					return err
				}
				if err := tx.Where("id IN ?", ids).Delete(&apiPO{}).Error; err != nil {
					return err
				}
			}
		}
		return nil
	})
}
