/*
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

import (
	"context"
	"encoding/json"
	"fmt"
	"time"

	"github.com/jmoiron/sqlx"
)

type AuditChange string

const (
	AuditCreateUser   AuditChange = "CREATE_USER"
	AuditDeleteUser   AuditChange = "DELETE_USER"
	AuditEditUser     AuditChange = "EDIT_USER"
	AuditAddEmail     AuditChange = "ADD_EMAIL"
	AuditDeleteEmail  AuditChange = "DELETE_EMAIL"
	AuditChangeVoters AuditChange = "CHANGE_VOTERS"
)

type Audit struct {
	ID          int64        `db:"id"`
	UserName    string       `db:"user_name"`
	UserAddress string       `db:"user_address"`
	Created     time.Time    `db:"created"`
	Change      *AuditChange `db:"change"`
	Reasoning   string       `db:"reasoning"`
	Details     string       `db:"details"`
}

func AuditLog(ctx context.Context, tx *sqlx.Tx, user *User, change AuditChange, reasoning string, details any) error {
	jsonDetails, err := json.Marshal(details)
	if err != nil {
		return fmt.Errorf("could not transform details to JSON: %w", err)
	}

	_, err = tx.ExecContext(
		ctx,
		`INSERT INTO audit (user_name, user_address, created, change, reasoning, details) VALUES (?, ?, ?, ?, ?, ?)`,
		user.Name, user.Reminder, time.Now().UTC(), change, reasoning, string(jsonDetails),
	)
	if err != nil {
		return errCouldNotExecuteQuery(err)
	}

	return nil
}

func emailChangeInfo(before, after []string) any {
	return struct {
		Before []string `json:"before"`
		After  []string `json:"after"`
	}{Before: before, After: after}
}

func voterChangeInfo(before []string, after []string) any {
	return struct {
		Before []string `json:"before"`
		After  []string `json:"after"`
	}{Before: before, After: after}
}

func userChangeInfo(before, after *User) any {
	beforeRoleNames, beforeAddresses := before.rolesAndAddresses()
	afterRoleNames, afterAddresses := after.rolesAndAddresses()

	type userInfo struct {
		Name      string   `json:"name"`
		Roles     []string `json:"roles"`
		Addresses []string `json:"addresses"`
		Reminder  string   `json:"reminder"`
	}

	details := struct {
		Before userInfo `json:"before"`
		After  userInfo `json:"after"`
	}{userInfo{
		Name:      before.Name,
		Roles:     beforeRoleNames,
		Addresses: beforeAddresses,
		Reminder:  before.Reminder.String,
	}, userInfo{
		Name:      after.Name,
		Roles:     afterRoleNames,
		Addresses: afterAddresses,
		Reminder:  after.Reminder.String,
	}}

	return details
}

func userCreateInfo(u *User) any {
	roleNames, addresses := u.rolesAndAddresses()

	type userInfo struct {
		Name      string   `json:"name"`
		Roles     []string `json:"roles"`
		Addresses []string `json:"addresses"`
		Reminder  string   `json:"reminder"`
	}

	details := struct {
		Created userInfo `json:"created"`
	}{Created: userInfo{
		Name:      u.Name,
		Roles:     roleNames,
		Addresses: addresses,
		Reminder:  u.Reminder.String,
	}}

	return details
}
