// Copyright (c) EZSCALE. // SPDX-License-Identifier: MPL-2.0 package provider import ( "context" "fmt" "terraform-provider-virtfusion/internal/client" "github.com/hashicorp/terraform-plugin-framework/datasource" "github.com/hashicorp/terraform-plugin-framework/datasource/schema" "github.com/hashicorp/terraform-plugin-framework/types" ) var ( _ datasource.DataSource = &SelfServiceReportDataSource{} _ datasource.DataSourceWithConfigure = &SelfServiceReportDataSource{} ) // NewSelfServiceReportDataSource returns a new self-service report data source. func NewSelfServiceReportDataSource() datasource.DataSource { return &SelfServiceReportDataSource{} } // SelfServiceReportDataSource defines the data source implementation. type SelfServiceReportDataSource struct { client *client.Client } // SelfServiceReportDataSourceModel describes the data source data model. type SelfServiceReportDataSourceModel struct { UserID types.Int64 `tfsdk:"user_id"` GroupID types.Int64 `tfsdk:"group_id"` ReportJSON types.String `tfsdk:"report_json"` } func (d *SelfServiceReportDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) { resp.TypeName = req.ProviderTypeName + "_self_service_report" } func (d *SelfServiceReportDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) { resp.Schema = schema.Schema{ MarkdownDescription: "Fetches a VirtFusion self-service report for a user and group.", Attributes: map[string]schema.Attribute{ "user_id": schema.Int64Attribute{ MarkdownDescription: "The user ID to fetch the report for.", Required: true, }, "group_id": schema.Int64Attribute{ MarkdownDescription: "The group ID to fetch the report for.", Required: true, }, "report_json": schema.StringAttribute{ MarkdownDescription: "The raw JSON response containing the report.", Computed: true, }, }, } } func (d *SelfServiceReportDataSource) Configure(_ context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) { if req.ProviderData == nil { return } c, ok := req.ProviderData.(*client.Client) if !ok { resp.Diagnostics.AddError( "Unexpected Data Source Configure Type", fmt.Sprintf("Expected *client.Client, got: %T.", req.ProviderData), ) return } d.client = c } func (d *SelfServiceReportDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { var data SelfServiceReportDataSourceModel resp.Diagnostics.Append(req.Config.Get(ctx, &data)...) if resp.Diagnostics.HasError() { return } rawResp, err := d.client.Get(ctx, fmt.Sprintf("/selfService/report/byUser/%d/group/%d", data.UserID.ValueInt64(), data.GroupID.ValueInt64())) if err != nil { resp.Diagnostics.AddError("Error Reading Self-Service Report", err.Error()) return } data.ReportJSON = types.StringValue(string(rawResp)) resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) }