package system

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

	"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) *system.ErrorRecord {
	return &system.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 *system.ErrorRecord) error {
	if !r.data.DatabaseReady() {
		// Silently ignore error records before the database is initialized.
		return nil
	}
	if v.Status == "" {
		v.Status = "未处理"
	}
	po := errorRecordPO{Form: v.Form, Info: v.Info, Level: v.Level, RequestID: v.RequestID, TraceID: v.TraceID, Solution: v.Solution, Status: v.Status}
	if err := r.data.DB().WithContext(ctx).Create(&po).Error; err != nil {
		return err
	}
	v.ID, v.CreatedAt, v.UpdatedAt = po.ID, po.CreatedAt, po.UpdatedAt
	return nil
}
func (r *auditQueryRepo) UpdateError(ctx context.Context, v *system.ErrorRecord) error {
	updates := make(map[string]any, 9)
	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) (*system.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 *system.ErrorRecord) ([]*system.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+"%")
		}
	}
	return listRows(db.Order("created_at desc"), page, size, rowQueryOptions{Paginate: true}, func(po errorRecordPO) *system.ErrorRecord {
		return errorFromPO(po)
	})
}
