using Books.Api.Domain.Companies;
using Books.Api.EventFlow.Repositories;
using Books.Api.GraphQL.Types;
using GraphQL;
using GraphQL.Types;

namespace Books.Api.GraphQL.Queries;

public class BooksQuery : ObjectGraphType
{
    public BooksQuery()
    {
        Name = "Query";
        Description = "Root query for the Books API";

        // companies: [CompanyType]
        Field<ListGraphType<CompanyType>>("companies")
            .Description("Get all companies")
            .ResolveAsync(async ctx =>
            {
                var repository = ctx.RequestServices!.GetRequiredService<ICompanyRepository>();
                return await repository.GetAllAsync(ctx.CancellationToken);
            });

        // company(id: ID!): CompanyType
        Field<CompanyType>("company")
            .Description("Get a company by ID")
            .Argument<NonNullGraphType<IdGraphType>>("id", "The company ID")
            .ResolveAsync(async ctx =>
            {
                var id = ctx.GetArgument<string>("id");
                var repository = ctx.RequestServices!.GetRequiredService<ICompanyRepository>();
                var companies = await repository.GetByIds([CompanyId.With(id)], ctx.CancellationToken);
                return companies.FirstOrDefault();
            });
    }
}
