// Copyright 2021 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.

// This file only contains version related variables and consts, all
// type definitions and functions shall not be implemented here.
// This file is excluded from CI tests.

package model

import (
	"strings"

	"gorm.io/gorm"
	"gorm.io/gorm/clause"

	"github.com/pingcap-inc/clinic/pkg/db"
)

func InsertLogSym(fileUUID, symtom, kibanaUrl string, kbList, jiraList []string) error {
	sym := db.LogSymptom{
		FileUUID: fileUUID,
		Symptom:  symtom,
		Kibana:   kibanaUrl,
		KB:       strings.Join(kbList, ","),
		Jira:     strings.Join(jiraList, ","),
	}
	return db.Transaction(func(txn *gorm.DB) error {
		return txn.Clauses(clause.OnConflict{
			Columns:   []clause.Column{{Name: "file_uuid"}, {Name: "symptom"}},
			DoUpdates: clause.AssignmentColumns([]string{"kibana", "kb", "jira"}),
		}).Create(sym).Error
	})
}

func ListLogSym(fileUUID string) ([]db.LogSymptom, error) {
	syms := []db.LogSymptom{}
	err := db.Transaction(func(txn *gorm.DB) error {
		err := txn.Where("file_uuid=?", fileUUID).Find(&syms).Error
		if err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return nil, err
	}

	return syms, nil
}
