/*
	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 api

import (
	"api-cds-search/cmd/database/table"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"time"
)

type CDSViewFieldJSON struct {
	Fields []table.CDSViewField `json:"fields"`
}

//TODO: "https://api.sap.com/api/1.0/container/CDSViews/artifacts?containerType=contentType&$filter=Type%20eq%20'CDSVIEW'&$top=" + fmt.Sprint(top) + "&$skip=" + fmt.Sprint(skip)

func GetCDSViewField(CDSViewTechnicalName table.TechnicalName) error {
	var json CDSViewFieldJSON
	path := string("https://api.sap.com/odata/1.0/catalog.svc/CdsViewsContent.CdsViews('" + CDSViewTechnicalName + "')/$value")
	fmt.Println("Getting: ", CDSViewTechnicalName)
	err := RequestJSON(path, &json)
	if err != nil {
		return err
	}

	for _, field := range json.Fields {
		field.CDSViewTechnicalName = CDSViewTechnicalName

		err := table.InsertOrReplaceCDSViewField(field)
		if err != nil {
			fmt.Println(err)
			continue
		}
	}
	return nil
}

func GetCDSViewFields() {

	cdsViews, _ := table.QueryAllCDSViewTechnicalNames()

	for _, cdsView := range *cdsViews {
		var json CDSViewFieldJSON
		path := string("https://api.sap.com/odata/1.0/catalog.svc/CdsViewsContent.CdsViews('" + cdsView + "')/$value")
		fmt.Println("Getting: ", cdsView)
		err := RequestJSON(path, &json)
		if err != nil {
			fmt.Println(cdsView, err)
			continue
		}
		for _, field := range json.Fields {
			field.CDSViewTechnicalName = cdsView

			err := table.InsertOrReplaceCDSViewField(field)
			if err != nil {
				fmt.Println(field.CDSViewTechnicalName, field.FieldName, err)
			}
		}
		time.Sleep(200 * time.Millisecond)
	}
}

func RequestJSON(url string, v any) error {
	response, err := http.Get(url)
	if err != nil {
		return err
	}

	responseData, err := io.ReadAll(response.Body)
	if err != nil {
		return err
	}

	if len(responseData) == 0 {
		return errors.New("empty response")
	}

	err = json.Unmarshal(responseData, v)
	if err != nil {
		return err
	}
	return nil
}