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

namespace Books.Api.GraphQL.Types;

public class UserCompanyAccessType : ObjectGraphType<UserCompanyAccessDto>
{
    public UserCompanyAccessType()
    {
        Name = "UserCompanyAccess";
        Description = "User access to a company";

        Field(x => x.Id).Description("Access record ID");
        Field(x => x.UserId).Description("User ID (Keycloak ID or email)");
        Field(x => x.CompanyId).Description("Company ID");
        Field<CompanyRoleEnumType>("role").Description("User's role for this company")
            .Resolve(ctx => ctx.Source.Role);
        Field(x => x.GrantedBy).Description("Who granted this access");
        Field(x => x.GrantedAt).Description("When access was granted");
        Field(x => x.IsActive).Description("Whether access is currently active");
        Field(x => x.RevokedAt, nullable: true).Description("When access was revoked");
        Field(x => x.RevokedBy, nullable: true).Description("Who revoked access");

        // Nested company data for convenience
        Field<CompanyType>("company")
            .Description("The company this access is for")
            .ResolveAsync(async ctx =>
            {
                var companyRepo = ctx.RequestServices!.GetRequiredService<ICompanyRepository>();
                var companies = await companyRepo.GetByIds([CompanyId.With(ctx.Source.CompanyId)], ctx.CancellationToken);
                return companies.FirstOrDefault();
            });
    }
}

public class CompanyRoleEnumType : EnumerationGraphType<CompanyRole>
{
    public CompanyRoleEnumType()
    {
        Name = "CompanyRole";
        Description = "Role a user can have for a company";

        Add("OWNER", CompanyRole.Owner, "Full access - can manage users, delete company");
        Add("ACCOUNTANT", CompanyRole.Accountant, "Can create journal entries, manage accounts, close fiscal years");
        Add("VIEWER", CompanyRole.Viewer, "Read-only access to all data");
    }
}
