package api

import (
	"agent/client/events"
	"context"
	"encoding/json"
)

type Project struct {
	Uuid         UUID            `json:"uuid"`
	Name         string          `json:"name"`
	Description  string          `json:"description"`
	System       bool            `json:"system"`
	Settings     map[string]any  `json:"settings"`
	CreatorUuid  UUID            `json:"creator_uuid"`
	EditorRights map[string]bool `json:"editor_rights"`
	Updated      int64           `json:"updated"`
	Created      int64           `json:"created"`
}

func ProjectCreate(ctx context.Context, client IClient, args ProjectCreateArgs) (res Project, err error) {
	event, err := EventProjectCreate(args)
	if err != nil {
		return res, nil
	}
	data, err := events.ExecuteAndGetData(ctx, client, event)
	if err != nil {
		return res, err
	}
	return res, json.Unmarshal(data, &res)
}

func ProjectDelete(ctx context.Context, client IClient, uuid UUID) error {
	event, err := EventProjectDelete(uuid)
	if err != nil {
		return err
	}
	_, err = events.ExecuteAndGetData(ctx, client, event)
	return err
}

func ProjectGet(ctx context.Context, client IClient, args ProjectGetArgs) (res Project, err error) {
	event, err := EventProjectGet(args)
	if err != nil {
		return res, nil
	}
	data, err := events.ExecuteAndGetData(ctx, client, event)
	if err != nil {
		return res, err
	}
	return res, json.Unmarshal(data, &res)
}

func ProjectUpdate(ctx context.Context, client IClient, args ProjectUpdateArgs) (res Project, err error) {
	event, err := EventProjectUpdate(args)
	if err != nil {
		return res, nil
	}
	data, err := events.ExecuteAndGetData(ctx, client, event)
	if err != nil {
		return res, err
	}
	return res, json.Unmarshal(data, &res)
}

func ProjectListAll(ctx context.Context, client IClient, search ...string) (res []Project, err error) {
	event, err := EventProjectListAll(search...)
	if err != nil {
		return res, nil
	}
	data, err := events.ExecuteAndGetData(ctx, client, event)
	if err != nil {
		return res, err
	}
	return res, json.Unmarshal(data, &res)
}

func ProjectListByAgent(ctx context.Context, client IClient,
	agentUuid UUID, search ...string,
) (res []Project, err error) {
	event, err := EventProjectListByAgent(agentUuid, search...)
	if err != nil {
		return res, nil
	}
	data, err := events.ExecuteAndGetData(ctx, client, event)
	if err != nil {
		return res, err
	}
	return res, json.Unmarshal(data, &res)
}

func ProjectListByArgs(ctx context.Context, client IClient, args ProjectListArgs) (res []Project, err error) {
	event, err := EventProjectList(args)
	if err != nil {
		return res, nil
	}
	data, err := events.ExecuteAndGetData(ctx, client, event)
	if err != nil {
		return res, err
	}
	return res, json.Unmarshal(data, &res)
}
