package model

import (
	"context"
	"fmt"

	"gorm.io/gorm"
)

type CaseRecord struct {
	CaseID             string  `gorm:"type:VARCHAR(64);not null"`
	GenerationID       string  `gorm:"type:VARCHAR(64);not null"`
	TraceID            string  `gorm:"type:VARCHAR(64);not null"`
	OperationID        string  `gorm:"type:VARCHAR(64);not null"`
	Category           string  `gorm:"type:VARCHAR(64);not null"`
	AffectedElement    string  `gorm:"type:VARCHAR(64);not null"`
	ElementType        string  `gorm:"type:VARCHAR(64);not null"`
	GenerationStrategy *string `gorm:"type:VARCHAR(64)"`
	Method             string  `gorm:"type:VARCHAR(16);not null"`
	Path               string  `gorm:"type:VARCHAR(256);not null"`
	Environment        string  `gorm:"type:JSON;not null"`
	Request            *string `gorm:"type:JSON;"`
	ExpectedStatus     int     `gorm:"not null"`
	ServiceName        string  `gorm:"type:VARCHAR(64);not null"`
	SpecCommitID       string  `gorm:"type:VARCHAR(64);not null"`
	Ignored            bool    `gorm:"not null"`
	Type               string  `gorm:"type:VARCHAR(64);not null"`
	SpecPRURL          string  `gorm:"column:spec_pr_url;type:VARCHAR(64);not null"`
}

func (CaseRecord) TableName() string {
	return "v_latest_openapi_test_cases"
}

type CaseRecordDAO struct {
	db *gorm.DB
}

func NewCaseRecordDAO(db *gorm.DB) (*CaseRecordDAO, error) {
	dao := &CaseRecordDAO{
		db: db,
	}
	return dao, nil
}

func (dao *CaseRecordDAO) ListCaseRecord(ctx context.Context, service string) ([]CaseRecord, error) {
	selector := dao.db.Model(&CaseRecord{}).Where("operation_id LIKE ?", fmt.Sprintf("%s_%%", service))
	rows, err := selector.Rows()
	if err != nil {
		return nil, err
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	defer rows.Close()

	out := make([]CaseRecord, 0)

	for rows.Next() {
		var record CaseRecord
		if err := dao.db.ScanRows(rows, &record); err != nil {
			return nil, err
		}
		out = append(out, record)
	}
	return out, nil
}
