package scim

import (
	"embed"
	"encoding/json"
	"fmt"
	"strings"

	"github.com/imulab/go-scim/pkg/v2/spec"
)

const (
	serviceProviderConfigPath = "public/service_provider_config.json"
	schemasPath               = "public/schemas"
	resourceTypesPath         = "public/resource_types"

	normalFileSuffix = ".json"
)

var (
	//go:embed public
	scimStaticResources embed.FS
)

func ParseServiceProviderConfig() (*spec.ServiceProviderConfig, error) {
	f, err := scimStaticResources.Open(serviceProviderConfigPath)
	if err != nil {
		return nil, err
	}
	config := new(spec.ServiceProviderConfig)
	err = json.NewDecoder(f).Decode(config)
	if err != nil {
		return nil, err
	}
	return config, nil
}

func ParseSchemas() ([]spec.Schema, error) {
	var schemas []spec.Schema
	dir, err := scimStaticResources.ReadDir(schemasPath)
	if err != nil {
		return nil, err
	}
	for _, df := range dir {
		if !strings.HasSuffix(df.Name(), normalFileSuffix) {
			continue
		}
		p := fmt.Sprintf("%s/%s", schemasPath, df.Name())
		f, err := scimStaticResources.Open(p)
		if err != nil {
			return nil, err
		}
		schema := new(spec.Schema)
		err = json.NewDecoder(f).Decode(schema)
		if err != nil {
			return nil, err
		}
		schemas = append(schemas, *schema)
	}
	return schemas, nil
}

func ParseResourceTypes() ([]spec.ResourceType, error) {
	var rts []spec.ResourceType
	dir, err := scimStaticResources.ReadDir(resourceTypesPath)
	if err != nil {
		return nil, err
	}
	for _, df := range dir {
		if !strings.HasSuffix(df.Name(), normalFileSuffix) {
			continue
		}
		p := fmt.Sprintf("%s/%s", resourceTypesPath, df.Name())
		f, err := scimStaticResources.Open(p)
		if err != nil {
			return nil, err
		}
		rt := new(spec.ResourceType)
		err = json.NewDecoder(f).Decode(rt)
		if err != nil {
			return nil, err
		}
		rts = append(rts, *rt)
	}
	return rts, nil
}
