using System.Net;
using Refit;
using Microsoft.Extensions.Options;
using Api.Clients.Api.Contracts;
using CvMatcher.Models.Responses;
using CvMatcher.Models.Settings;
using CvMatcher.Models.Requests;

namespace Api.Clients.Api;

public sealed class RagApiClient : IRagApiClient
{
    private readonly IRefitRagApi _refit;

    public RagApiClient(IRefitRagApi refit, IOptions<RagApiSettings> options)
    {
        _refit = refit;
    }

    public async Task<RagIndexResponse> IndexCvPdfAsync(IFormFile file, CancellationToken ct)
    {
        await using var stream = file.OpenReadStream();
        var part = new StreamPart(stream, file.FileName, "application/pdf");
        return await _refit.IndexDocumentAsync(part, "cv", file.FileName, ct);
    }

    public async Task<RagIndexResponse> IndexJobTextAsync(string text, string? url, string? title, CancellationToken ct)
    {
        return await _refit.IndexDocumentWithTextAsync(text, "job", title ?? "Job description", url, ct);
    }

    public async Task<RagDocumentDetails?> GetDocumentAsync(string documentId, CancellationToken ct)
    {
        try
        {
            return await _refit.GetDocumentAsync(documentId, ct);
        }
        catch (ApiException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
        {
            return null;
        }
    }

    public async Task<RagSearchResponse> SearchAsync(RagSearchRequest request, CancellationToken ct)
    {
        return await _refit.SearchAsync(request, ct);
    }
}
