package br_svc

import (
	"context"
	"encoding/json"
	"time"

	"github.com/tidbcloud/serverless-service/idl/pbgen/proto/console"
	"github.com/tidbcloud/serverless-service/internal/service/console_auditlog"
	"github.com/tidbcloud/tiinf/sdk/auditlog"
)

func recordDeleteRecycledInstanceBackupAuditLog(
	ctx context.Context,
	req *console.DeleteRecycledInstanceBackupRequest,
	err error,
) {
	details := auditlog.Details{
		auditlog.KeyBackupID: req.GetBackupId(),
	}
	console_auditlog.SubmitWithStringIDs(
		ctx,
		auditlog.EventDeleteBackup,
		req.GetOrgId(),
		"",
		req.GetClusterId(),
		details,
		err,
	)
}

type RestoreAuditLogDetail struct {
	RestoreMode     *RestoreMode `json:"restore_mode,omitempty"`
	TargetClusterID string       `json:"target_cluster_id"`
	Error           string       `json:"error,omitempty"`
}

type RestoreMode struct {
	Snapshot    *Snapshot    `json:"snapshot,omitempty"`
	PointInTime *PointInTime `json:"point_in_time,omitempty"`
}

type Snapshot struct {
	BackupID string `json:"backup_id,omitempty"`
}

type PointInTime struct {
	ClusterID  string    `json:"cluster_id,omitempty"`
	BackupTime time.Time `json:"backup_time"`
}

func ConvertToAuditLogDetail(a any) (auditlog.Details, error) {
	marshal, err := json.Marshal(a)
	if err != nil {
		return nil, err
	}
	details := auditlog.Details{}
	if err := json.Unmarshal(marshal, &details); err != nil {
		return nil, err
	}
	return details, nil
}
