// Copyright 2022 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
	"context"
	"net/http"
	"os"

	"github.com/aws/aws-lambda-go/lambda"
	"github.com/awslabs/aws-lambda-go-api-proxy/httpadapter"
	"github.com/gorilla/mux"
	"github.com/pingcap/fn"
	"github.com/pingcap/log"

	"github.com/pingcap-inc/compute-engine/pkg/database"
	"github.com/pingcap-inc/compute-engine/pkg/service"
)

type CTX_KEY string

const (
	InstanceKey CTX_KEY = "SCHED_INST"
)

func main() {
	log.Info("scheduler init...")
	m := database.InitTaskModel()
	defer m.Close()

	r := mux.NewRouter()

	// Inject scheduler service into context
	fn.Plugin(func(ctx context.Context, req *http.Request) (context.Context, error) {
		// It's ok to not release resources allocated by scheduler service here, since its lifecycle is the same as the lambda function.
		s := service.NewLambdaScheduler(m)
		ctx = context.WithValue(ctx, InstanceKey, s)
		return ctx, nil
	})

	fn.SetErrorEncoder(func(ctx context.Context, err error) interface{} {
		// TODO: implement semantic error
		return map[string]interface{}{
			"error": err.Error(),
		}
	})

	r.Handle("/tasks", fn.Wrap(ListTask)).Methods("GET")
	r.Handle("/tasks/{task}/sync", fn.Wrap(TriggerTaskSync)).Methods("POST")
	r.Handle("/tasks/{task}/async", fn.Wrap(TriggerTaskAsync)).Methods("POST")
	r.Handle("/tasks/{task}", fn.Wrap(SearchInstance)).Methods("POST")
	r.Handle("/tasks/{task}", fn.Wrap(SearchInstanceLight)).Methods("GET")
	r.Handle("/instances/{instance}", fn.Wrap(GetInstance)).Methods("GET")
	r.Handle("/instances/{instance}/sync", fn.Wrap(RetryTaskSync)).Methods("PUT")
	r.Handle("/instances/{instance}/async", fn.Wrap(RetryTaskAsync)).Methods("PUT")

	// use different proxy format by env variable
	if os.Getenv("CE_DEBUG") != "" {
		http.ListenAndServe(":8080", r)
	} else if os.Getenv("PROXY_FORMAT") == "v1" {
		lambda.Start(httpadapter.New(r).ProxyWithContext)
	} else if os.Getenv("PROXY_FORMAT") == "alb" {
		lambda.Start(httpadapter.NewALB(r).ProxyWithContext)
	} else {
		lambda.Start(httpadapter.NewV2(r).ProxyWithContext)
	}
}
