package system

import (
	"context"
	"time"

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

	"gorm.io/gorm"
)

type errorRecordPO struct {
	ID        uint `gorm:"primaryKey"`
	CreatedAt time.Time
	UpdatedAt time.Time
	DeletedAt gorm.DeletedAt `gorm:"index"`
	Form      *string        `gorm:"type:text"`
	Info      *string        `gorm:"type:text"`
	Level     string
	RequestID string  `gorm:"index"`
	TraceID   string  `gorm:"index"`
	Solution  *string `gorm:"type:text"`
	Status    string  `gorm:"default:未处理"`
}

func (errorRecordPO) TableName() string { return "sys_error" }

func errorFromPO(v errorRecordPO) *biz.ErrorRecord {
	return &biz.ErrorRecord{ID: v.ID, CreatedAt: v.CreatedAt, UpdatedAt: v.UpdatedAt, Form: v.Form, Info: v.Info, Level: v.Level, RequestID: v.RequestID, TraceID: v.TraceID, Solution: v.Solution, Status: v.Status}
}
func (r *auditRecorderRepo) CreateError(ctx context.Context, v *biz.ErrorRecord) error {
	if !r.data.DatabaseReady() {
		// Silently ignore error records before the database is initialized.
		return nil
	}
	if v.Status == "" {
		v.Status = "未处理"
	}
	return r.data.DB().WithContext(ctx).Create(&errorRecordPO{ID: v.ID, CreatedAt: v.CreatedAt, UpdatedAt: v.UpdatedAt, Form: v.Form, Info: v.Info, Level: v.Level, RequestID: v.RequestID, TraceID: v.TraceID, Solution: v.Solution, Status: v.Status}).Error
}
func (r *auditQueryRepo) UpdateError(ctx context.Context, v *biz.ErrorRecord) error {
	updates := make(map[string]any, 9)
	if v.ID != 0 {
		updates["id"] = v.ID
	}
	if !v.CreatedAt.IsZero() {
		updates["created_at"] = v.CreatedAt
	}
	if v.Form != nil {
		updates["form"] = v.Form
	}
	if v.Info != nil {
		updates["info"] = v.Info
	}
	if v.Level != "" {
		updates["level"] = v.Level
	}
	if v.RequestID != "" {
		updates["request_id"] = v.RequestID
	}
	if v.TraceID != "" {
		updates["trace_id"] = v.TraceID
	}
	if v.Solution != nil {
		updates["solution"] = v.Solution
	}
	if v.Status != "" {
		updates["status"] = v.Status
	}
	return r.data.DB().WithContext(ctx).Model(&errorRecordPO{}).Where("id = ?", v.ID).Updates(updates).Error
}
func (r *auditQueryRepo) DeleteErrors(ctx context.Context, ids []uint) error {
	return r.data.DB().WithContext(ctx).Delete(&errorRecordPO{}, ids).Error
}
func (r *auditQueryRepo) FindError(ctx context.Context, id uint) (*biz.ErrorRecord, error) {
	var po errorRecordPO
	if err := r.data.DB().WithContext(ctx).First(&po, id).Error; err != nil {
		return nil, err
	}
	return errorFromPO(po), nil
}
func (r *auditQueryRepo) ListErrors(ctx context.Context, page, size int, q *biz.ErrorRecord) ([]*biz.ErrorRecord, int64, error) {
	db := r.data.DB().WithContext(ctx).Model(&errorRecordPO{})
	if q != nil {
		if len(q.CreatedAtRange) == 2 {
			db = db.Where("created_at BETWEEN ? AND ?", q.CreatedAtRange[0], q.CreatedAtRange[1])
		}
		if q.Form != nil && *q.Form != "" {
			db = db.Where("form = ?", *q.Form)
		}
		if q.Info != nil && *q.Info != "" {
			db = db.Where("info LIKE ?", "%"+*q.Info+"%")
		}
	}
	var total int64
	if err := db.Count(&total).Error; err != nil {
		return nil, 0, err
	}
	var pos []errorRecordPO
	if err := pagination.Apply(db.Order("created_at desc"), page, size, 100).Find(&pos).Error; err != nil {
		return nil, 0, err
	}
	out := make([]*biz.ErrorRecord, 0, len(pos))
	for _, po := range pos {
		out = append(out, errorFromPO(po))
	}
	return out, total, nil
}
