package graph

// This file will be automatically regenerated based on the schema, any resolver implementations
// will be copied through when generating and any unknown code will be moved to the end.
// Code generated by github.com/99designs/gqlgen version v0.17.63

import (
	"context"
	"log/slog"
	"myapp/graph/model"
	"time"

	"github.com/antonputra/go-utils/util"
	"github.com/google/uuid"
	"github.com/prometheus/client_golang/prometheus"
)

// CreateDevice is the resolver for the createDevice field.
func (r *mutationResolver) CreateDevice(ctx context.Context, input model.NewDevice) (*model.Device, error) {
	now := time.Now().Format(time.RFC3339Nano)

	// Create a device based on the input from the query.
	d := &model.Device{
		UUID:      uuid.New().String(),
		Mac:       input.Mac,
		Firmware:  input.Firmware,
		CreatedAt: now,
		UpdatedAt: now,
	}

	err := d.Insert(ctx, r.Db, r.M)
	if err != nil {
		r.M.Errors.With(prometheus.Labels{"op": "insert", "db": "postgres"}).Add(1)
		util.Warn(err, "failed to save device in postgres")
		return nil, err
	}
	slog.Debug("device saved in postgres", "id", d.ID, "mac", d.Mac, "firmware", d.Firmware)

	// Return the device to the client.
	return d, nil
}

// Device is the resolver for the device field.
func (r *queryResolver) Device(ctx context.Context) ([]*model.Device, error) {
	// Instead of searching for a device by ID in the memory database,
	// just return a hardcoded device to the client with the required ID.
	devices := []*model.Device{
		{
			ID:        1,
			UUID:      "9add349c-c35c-4d32-ab0f-53da1ba40a2a",
			Mac:       "EF-2B-C4-F5-D6-34",
			Firmware:  "2.1.5",
			CreatedAt: "2024-05-28T15:21:51.137Z",
			UpdatedAt: "2024-05-28T15:21:51.137Z",
		},
		{
			ID:        2,
			UUID:      "d2293412-36eb-46e7-9231-af7e9249fffe",
			Mac:       "E7-34-96-33-0C-4C",
			Firmware:  "1.0.3",
			CreatedAt: "2024-01-28T15:20:51.137Z",
			UpdatedAt: "2024-01-28T15:20:51.137Z",
		},
		{
			ID:        3,
			UUID:      "eee58ca8-ca51-47a5-ab48-163fd0e44b77",
			Mac:       "68-93-9B-B5-33-B9",
			Firmware:  "4.3.1",
			CreatedAt: "2024-08-28T15:18:21.137Z",
			UpdatedAt: "2024-08-28T15:18:21.137Z",
		},
	}

	return devices, nil
}

// Mutation returns MutationResolver implementation.
func (r *Resolver) Mutation() MutationResolver { return &mutationResolver{r} }

// Query returns QueryResolver implementation.
func (r *Resolver) Query() QueryResolver { return &queryResolver{r} }

type mutationResolver struct{ *Resolver }
type queryResolver struct{ *Resolver }
