/* 
 * Copyright (c)2009-2025 DemiVision, LLC. All Rights Reserved. The information 
 * herein is the CONFIDENTIAL and PROPRIETARY information of DemiVision, LLC. 
 */

using System.Text.Json;
using System.Text.Json.Serialization;

using RestSharp;
using RestSharp.Serializers.Json;

using DXLib.Log;

namespace iStatVball3;

/*
 * Provides convenience methods for accessing the Bound REST API. Methods are provided for retrieving the state list,
 * school list, and for POSTing match stats.
 */
public static class VBApi
{
	/* Constants */
	private const string BaseURL = "https://manager.gobound.com/api/";

	/* Methods */

	// GETs full list of supported states
	public static async Task<List<VBState>> GetStates()
	{
        RestRequest request = new( "state" );

        // HTTP GET state list
        return await GetClient().GetAsync<List<VBState>>( request );
    }

    // GETs full list of school names and IDs for specified state
    public static async Task<List<VBSchool>> GetSchools( string state )
	{
		RestRequest request = new( "state/{state}/schools" );

		// Restrict query to state
		request.AddUrlSegment( "state", state );

		// HTTP GET school list
		return await GetClient().GetAsync<List<VBSchool>>( request );
	}

	// POSTs match stats for individual match
	public static async Task<bool> UploadStats( string schoolId, VBExport export )
	{
		RestRequest request = new( "/import/stats/istatv3/v1/volleyball/{schoolId}" );

		// Configure request
		request.AddUrlSegment( "schoolId", schoolId );

		// Add serialized JSON body
		request.AddJsonBody( export );

		// POST to Varsity Bound
		RestResponse response = await GetClient().PostAsync( request );

		bool success = response is { IsSuccessful: true };

		// Debug
		if ( !success )
		{
			DXLog.Error( "bound.uploadstats", "response:{0}", response.Content );
		}

		return success;
	}

	// Returns HTTP client used for all requests
	private static RestClient GetClient()
	{
		RestClient client = new( BaseURL, configureSerialization: s => s.UseSystemTextJson( new JsonSerializerOptions
		{
			DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
			PropertyNameCaseInsensitive = true,
			PropertyNamingPolicy = JsonNamingPolicy.CamelCase
		}));

		return client;
	}
}

//
