/*
	Copyright (C) 2025  snoutie
	Authors: snoutie (copyright@achtarmig.org)
	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU Affero General Public License as published
	by the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Affero General Public License for more details.

	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

package table

import (
	"api-cds-search/cmd/database"
	_ "embed"
)

type CDSViewField struct {
	CDSViewTechnicalName string
	FieldName            string `json:"fieldname"`
	Description          string `json:"description"`
	DataType             string `json:"datatype"`
	FieldLength          string `json:"fieldlength"`
}

//go:embed sql/query_cds_view_fields.sql
var query_cds_view_fields string

func GetCDSViewFields(CDSViewTechnicalName string) (*[]CDSViewField, error) {
	rows, err := database.DB.Query(query_cds_view_fields, CDSViewTechnicalName)
	if err != nil {
		return nil, err
	}
	var fields []CDSViewField = make([]CDSViewField, 0)
	for rows.Next() {
		var field CDSViewField
		err := rows.Scan(&field.CDSViewTechnicalName, &field.FieldName, &field.Description, &field.DataType, &field.FieldLength)
		if err != nil {
			return nil, err
		}
		fields = append(fields, field)
	}
	return &fields, nil
}

//go:embed sql/query_cds_view_number_of_fields.sql
var query_cds_view_number_of_fields string

func GetCDSViewNumberOfFields(CDSViewTechnicalName string) (int, error) {
	rows, err := database.DB.Query(query_cds_view_number_of_fields, CDSViewTechnicalName)
	if err != nil {
		return 0, err
	}

	var numberOfFields int = 0
	for rows.Next() {
		err := rows.Scan(&numberOfFields)
		if err != nil {
			return 0, err
		}
	}
	return numberOfFields, nil
}

//go:embed sql/insert_or_replace_cds_view_field.sql
var insert_or_replace_cds_view_field string

func InsertOrReplaceCDSViewField(field CDSViewField) error {
	_, err := database.DB.Exec(insert_or_replace_cds_view_field, field.CDSViewTechnicalName, field.FieldName, field.Description, field.DataType, field.FieldLength)
	if err != nil {
		return err
	}
	return nil
}