/*
Copyright 2022 CAcert Inc.
SPDX-License-Identifier: Apache-2.0

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,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package models_test

import (
	"context"
	"database/sql"
	"log"
	"os"
	"path"
	"testing"
	"time"

	"github.com/jmoiron/sqlx"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"git.cacert.org/cacert-boardvoting/internal"
	"git.cacert.org/cacert-boardvoting/internal/models"
)

func prepareTestDb(t *testing.T) *sqlx.DB {
	t.Helper()

	testDir := t.TempDir()

	db, err := sql.Open("sqlite3", path.Join(testDir, "test.sqlite"))
	require.NoError(t, err)

	dbx := sqlx.NewDb(db, "sqlite3")

	logger := log.New(os.Stdout, "", log.LstdFlags)

	err = internal.InitializeDb(dbx.DB, logger)
	require.NoError(t, err)

	return dbx
}

func TestDecisionModel_Create(t *testing.T) {
	dbx := prepareTestDb(t)

	dm := models.MotionModel{DB: dbx}

	v := &models.User{
		ID:       1, // sqlite does not check referential integrity. Might fail with a foreign key index.
		Name:     "test voter",
		Reminder: sql.NullString{String: "test+voter@example.com", Valid: true},
	}

	id, err := dm.Create(
		context.Background(),
		v,
		models.VoteTypeMotion,
		"test motion",
		"I move that we should test more",
		time.Now(),
		time.Now().AddDate(0, 0, 7),
	)
	assert.NoError(t, err)
	assert.NotEmpty(t, id)
}

func TestDecisionModel_GetNextPendingDecisionDue(t *testing.T) {
	dbx := prepareTestDb(t)

	dm := models.MotionModel{DB: dbx}

	var (
		nextDue *time.Time
		err     error
	)

	nextDue, err = dm.NextPendingDue(context.Background(), time.Now().UTC())
	assert.NoError(t, err)
	assert.Empty(t, nextDue)

	v := &models.User{
		ID:       1, // sqlite does not check referential integrity. Might fail with a foreign key index.
		Name:     "test voter",
		Reminder: sql.NullString{String: "test+voter@example.com", Valid: true},
	}

	due := time.Now().Add(10 * time.Minute)

	ctx := context.Background()

	_, err = dm.Create(ctx, v, models.VoteTypeMotion, "test motion", "I move that we should test more", time.Now(), due)
	require.NoError(t, err)

	nextDue, err = dm.NextPendingDue(ctx, time.Now().UTC())
	assert.NoError(t, err)
	assert.NotEmpty(t, nextDue)

	assert.Equal(t, due.UTC(), *nextDue)
}
