package system

import (
	"context"
	"errors"
	"strconv"
	"time"

	"kra/internal/biz"
	"kra/pkg/database/pagination"

	"gorm.io/gorm"
)

type apiRepo struct{ data Provider }

func NewAPIRepo(data Provider) biz.APIRepo { return &apiRepo{data: data} }

type apiPO struct {
	ID          uint `gorm:"primaryKey"`
	CreatedAt   time.Time
	UpdatedAt   time.Time
	DeletedAt   gorm.DeletedAt `gorm:"index"`
	Path        string
	Description string
	APIGroup    string `gorm:"column:api_group"`
	Method      string
}

func (apiPO) TableName() string { return "sys_apis" }

type ignoredAPIPO struct {
	ID        uint `gorm:"primaryKey"`
	CreatedAt time.Time
	UpdatedAt time.Time
	DeletedAt gorm.DeletedAt `gorm:"index"`
	Path      string
	Method    string `gorm:"default:POST"`
}

func (ignoredAPIPO) TableName() string { return "sys_ignore_apis" }

type authorityAPIPO struct {
	AuthorityID uint `gorm:"primaryKey;column:authority_id"`
	APIID       uint `gorm:"primaryKey;column:api_id"`
}

func (authorityAPIPO) TableName() string { return "sys_authority_apis" }

func apiFromPO(po apiPO) *biz.API {
	return &biz.API{ID: po.ID, CreatedAt: po.CreatedAt, UpdatedAt: po.UpdatedAt, Path: po.Path, Description: po.Description, APIGroup: po.APIGroup, Method: po.Method}
}
func (r *apiRepo) CreateAPI(ctx context.Context, v *biz.API) error {
	po := apiPO{Path: v.Path, Description: v.Description, APIGroup: v.APIGroup, Method: v.Method}
	var count int64
	if err := r.data.DB().WithContext(ctx).Model(&apiPO{}).Where("path = ? AND method = ?", po.Path, po.Method).Count(&count).Error; err != nil {
		return err
	}
	if count > 0 {
		return errors.New("存在相同api")
	}
	if err := r.data.DB().WithContext(ctx).Create(&po).Error; err != nil {
		return err
	}
	v.ID, v.CreatedAt, v.UpdatedAt, v.Method = po.ID, po.CreatedAt, po.UpdatedAt, po.Method
	return nil
}
func (r *apiRepo) UpdateAPI(ctx context.Context, v *biz.API) error {
	db := r.data.DB().WithContext(ctx)
	var old apiPO
	if err := db.First(&old, v.ID).Error; err != nil {
		return err
	}
	method := v.Method
	if old.Path != v.Path || old.Method != method {
		var count int64
		if err := db.Model(&apiPO{}).Where("id <> ? AND path = ? AND method = ?", v.ID, v.Path, method).Count(&count).Error; err != nil {
			return err
		}
		if count > 0 {
			return errors.New("存在相同api路径")
		}
	}
	// Authorization is stored independently in casbin_rule and updates every
	// matching policy when an API path or method changes.
	if err := db.Model(&casbinRulePO{}).
		Where("ptype = ? AND v1 = ? AND v2 = ?", "p", old.Path, old.Method).
		Updates(map[string]any{"v1": v.Path, "v2": method}).Error; err != nil {
		return err
	}
	return db.Model(&old).Updates(map[string]any{"path": v.Path, "description": v.Description, "api_group": v.APIGroup, "method": method}).Error
}
func (r *apiRepo) DeleteAPIs(ctx context.Context, ids []uint) error {
	return r.data.DB().WithContext(ctx).Transaction(func(tx *gorm.DB) error {
		var apis []apiPO
		if err := tx.Where("id IN ?", ids).Find(&apis).Error; err != nil {
			return err
		}
		for _, api := range apis {
			if err := deletePoliciesForPath(tx, api.Path, api.Method); err != nil {
				return err
			}
		}
		// Keep the legacy relation table clean for upgraded installations. It is
		// no longer the authorization source.
		if err := tx.Where("api_id IN ?", ids).Delete(&authorityAPIPO{}).Error; err != nil {
			return err
		}
		return tx.Delete(&apiPO{}, ids).Error
	})
}
func (r *apiRepo) FindAPI(ctx context.Context, id uint) (*biz.API, error) {
	var po apiPO
	if err := r.data.DB().WithContext(ctx).First(&po, id).Error; err != nil {
		return nil, err
	}
	return apiFromPO(po), nil
}
func (r *apiRepo) ListAPIs(ctx context.Context, page, size int, q *biz.API) ([]*biz.API, int64, error) {
	db := r.data.DB().WithContext(ctx).Model(&apiPO{})
	if q != nil && q.StrictAll {
		config := r.data.Runtime().Admin()
		if actor, ok := biz.ActorFromContext(ctx); ok && config != nil && config.System != nil && config.System.UseStrictAuth {
			var authority authorityPO
			if err := r.data.DB().WithContext(ctx).Where("authority_id = ?", actor.AuthorityID).First(&authority).Error; err != nil {
				return nil, 0, err
			}
			if authority.ParentID != nil && *authority.ParentID != 0 {
				// Strict mode filters API metadata by the actor's persisted
				// Casbin policies, matching on path/method rather than an API FK.
				db = db.Where(`EXISTS (
					SELECT 1 FROM casbin_rule cr
					WHERE cr.ptype = 'p' AND cr.v0 = ?
					  AND cr.v1 = sys_apis.path AND cr.v2 = sys_apis.method
				)`, strconv.FormatUint(uint64(actor.AuthorityID), 10))
			}
		}
	}
	if q != nil {
		if q.Path != "" {
			db = db.Where("path LIKE ?", "%"+q.Path+"%")
		}
		if q.Description != "" {
			db = db.Where("description LIKE ?", "%"+q.Description+"%")
		}
		if q.APIGroup != "" {
			db = db.Where("api_group = ?", q.APIGroup)
		}
		if q.Method != "" {
			db = db.Where("method = ?", q.Method)
		}
	}
	var total int64
	if err := db.Count(&total).Error; err != nil {
		return nil, 0, err
	}
	order := "id desc"
	if q != nil && q.OrderKey != "" {
		allowed := map[string]bool{"id": true, "path": true, "api_group": true, "description": true, "method": true}
		if !allowed[q.OrderKey] {
			return nil, 0, errors.New("非法的排序字段: " + q.OrderKey)
		}
		order = q.OrderKey
		if q.Desc {
			order += " desc"
		}
	}
	var pos []apiPO
	query := db.Order(order)
	if q == nil || !q.StrictAll {
		query = pagination.ApplyRequired(query, page, size, 100)
	}
	if err := query.Find(&pos).Error; err != nil {
		return nil, 0, err
	}
	out := make([]*biz.API, 0, len(pos))
	for _, po := range pos {
		out = append(out, apiFromPO(po))
	}
	return out, total, nil
}
