package postgres

import (
	"context"

	db "code.justin.tv/eventbus/controlplane/internal/db"

	"github.com/jmoiron/sqlx"
)

const (
	AuditLogsTableName = "audit_logs"

	auditLogsByServiceIDQuery = "SELECT id, user_name, service_id, resource_name, resource_type, result, action, timestamp, before, after FROM audit_logs WHERE service_id=$1 ORDER BY timestamp DESC"

	createAuditLogQuery = "INSERT INTO audit_logs (user_name, service_id, resource_name, resource_type, result, action, timestamp, before, after) values (:user_name, :service_id, :resource_name, :resource_type, :result, :action, :timestamp, :before, :after) RETURNING id"
)

func (pg *PostgresDB) AuditLogCreate(ctx context.Context, al *db.AuditLog) (int, error) {
	var id int
	namedQuery, err := pg.writer.PrepareNamedContext(ctx, createAuditLogQuery)
	if err != nil {
		return -1, err
	}

	err = namedQuery.QueryRowxContext(ctx, al).Scan(&id)
	return id, err
}

func (pg *PostgresDB) AuditLogCreateTx(ctx context.Context, tx *sqlx.Tx, al *db.AuditLog) (int, error) {
	var id int
	namedQuery, err := tx.PrepareNamedContext(ctx, createAuditLogQuery)
	if err != nil {
		return -1, err
	}

	err = namedQuery.QueryRowxContext(ctx, al).Scan(&id)
	return id, err
}

func (pg *PostgresDB) AuditLogsByServiceID(ctx context.Context, serviceID int) ([]*db.AuditLog, error) {
	var auditlogs []*db.AuditLog
	err := pg.reader.SelectContext(ctx, &auditlogs, auditLogsByServiceIDQuery, serviceID)
	return auditlogs, err
}
