package repository

import (
	"context"

	dbent "github.com/Wei-Shaw/sub2api/ent"
	"github.com/Wei-Shaw/sub2api/internal/service"
)

type requestCaptureLogRepository struct {
	client *dbent.Client
}

// NewRequestCaptureLogRepository 创建请求捕获日志仓储实例。
func NewRequestCaptureLogRepository(client *dbent.Client) service.RequestCaptureLogRepository {
	return &requestCaptureLogRepository{client: client}
}

func (r *requestCaptureLogRepository) Create(ctx context.Context, params service.CreateRequestCaptureLogParams) (int64, error) {
	q := r.client.RequestCaptureLog.Create().
		SetAPIKeyID(params.APIKeyID).
		SetUserID(params.UserID)

	if params.RequestID != "" {
		q = q.SetRequestID(params.RequestID)
	}
	if params.Path != "" {
		q = q.SetPath(params.Path)
	}
	if params.Method != "" {
		q = q.SetMethod(params.Method)
	}
	if params.IPAddress != "" {
		q = q.SetIPAddress(params.IPAddress)
	}
	if params.RequestBody != "" {
		q = q.SetRequestBody(params.RequestBody)
	}
	if params.NFSFilePath != "" {
		q = q.SetNfsFilePath(params.NFSFilePath)
	}

	row, err := q.Save(ctx)
	if err != nil {
		return 0, err
	}
	return row.ID, nil
}

func (r *requestCaptureLogRepository) UpdateResponseBody(ctx context.Context, id int64, responseBody string) error {
	return r.client.RequestCaptureLog.UpdateOneID(id).
		SetResponseBody(responseBody).
		Exec(ctx)
}
