package postgres

import (
	"context"
	"database/sql"
	"encoding/json"

	"switchboard-core/models"
	"switchboard-core/store"
)

type AuditStore struct{}

func NewAuditStore() *AuditStore { return &AuditStore{} }

func (s *AuditStore) Log(ctx context.Context, entry *models.AuditEntry) error {
	metadataJSON := ToJSON(entry.Metadata)
	return DB.QueryRowContext(ctx, `
		INSERT INTO audit_log (actor_id, action, resource_type, resource_id, metadata, ip_address, user_agent)
		VALUES ($1, $2, $3, $4, $5, $6, $7)
		RETURNING id, created_at`,
		models.NullString(entry.ActorID), entry.Action, entry.ResourceType,
		entry.ResourceID, metadataJSON, entry.IPAddress, entry.UserAgent,
	).Scan(&entry.ID, &entry.CreatedAt)
}

func (s *AuditStore) List(ctx context.Context, opts store.AuditListOptions) ([]models.AuditEntry, int, error) {
	b := NewSelect(`al.id, al.actor_id, COALESCE(u.username, '') AS actor_name,
		al.action, al.resource_type, al.resource_id, al.metadata,
		al.ip_address, al.user_agent, al.created_at`, "audit_log al")
	b.Join("LEFT JOIN users u ON al.actor_id = u.id")

	if opts.TeamID != "" {
		b.Where("al.actor_id IN (SELECT user_id FROM team_members WHERE team_id = ?)", opts.TeamID)
	}
	if opts.ActorID != "" {
		b.Where("al.actor_id = ?", opts.ActorID)
	}
	if opts.Action != "" {
		b.Where("al.action = ?", opts.Action)
	}
	if opts.ResourceType != "" {
		b.Where("al.resource_type = ?", opts.ResourceType)
	}
	if opts.ResourceID != "" {
		b.Where("al.resource_id = ?", opts.ResourceID)
	}
	if opts.Since != nil {
		b.Where("al.created_at >= ?", *opts.Since)
	}
	if opts.Until != nil {
		b.Where("al.created_at <= ?", *opts.Until)
	}

	// Count
	countQ, countArgs := b.CountBuild()
	var total int
	DB.QueryRowContext(ctx, countQ, countArgs...).Scan(&total)

	// Results
	if opts.Sort == "" {
		b.OrderBy("al.created_at", "DESC")
	}
	b.Paginate(opts.ListOptions)

	q, args := b.Build()
	rows, err := DB.QueryContext(ctx, q, args...)
	if err != nil {
		return nil, 0, err
	}
	defer rows.Close()

	var result []models.AuditEntry
	for rows.Next() {
		var e models.AuditEntry
		var actorID, actorName sql.NullString
		var metadataJSON []byte
		err := rows.Scan(&e.ID, &actorID, &actorName, &e.Action, &e.ResourceType, &e.ResourceID,
			&metadataJSON, &e.IPAddress, &e.UserAgent, &e.CreatedAt)
		if err != nil {
			return nil, 0, err
		}
		e.ActorID = NullableStringPtr(actorID)
		if actorName.Valid && actorName.String != "" {
			e.ActorName = &actorName.String
		}
		json.Unmarshal(metadataJSON, &e.Metadata)
		result = append(result, e)
	}
	return result, total, rows.Err()
}

func (s *AuditStore) ListActions(ctx context.Context) ([]string, error) {
	rows, err := DB.QueryContext(ctx,
		`SELECT DISTINCT action FROM audit_log ORDER BY action ASC`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var actions []string
	for rows.Next() {
		var a string
		if rows.Scan(&a) == nil {
			actions = append(actions, a)
		}
	}
	if actions == nil {
		actions = []string{}
	}
	return actions, rows.Err()
}
