package repository

import (
	"context"
	"encoding/json"
	"lune/talentscale/internal/domain"
	"github.com/jackc/pgx/v5/pgxpool"
)

type postgresSystemLogRepository struct {
	db *pgxpool.Pool
}

func NewPostgresSystemLogRepository(db *pgxpool.Pool) domain.SystemLogRepository {
	return &postgresSystemLogRepository{db: db}
}

func (r *postgresSystemLogRepository) Create(ctx context.Context, logEntry *domain.SystemLog) error {
	query := `
		INSERT INTO system_logs (
			level, message, context, source, action, 
			user_id, company_id, ip_address, user_agent, 
			status_code, duration_ms, request_id, endpoint, 
			method, error_stack, created_at
		) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16)
	`
	
	contextJSON, _ := json.Marshal(logEntry.Context)
	if logEntry.Context == nil {
		contextJSON = []byte("{}")
	}

	_, err := r.db.Exec(ctx, query,
		logEntry.Level, logEntry.Message, contextJSON, logEntry.Source, logEntry.Action,
		logEntry.UserID, logEntry.CompanyID, logEntry.IPAddress, logEntry.UserAgent,
		logEntry.StatusCode, logEntry.DurationMs, logEntry.RequestID, logEntry.Endpoint,
		logEntry.Method, logEntry.ErrorStack, logEntry.CreatedAt,
	)
	
	return err
}

func (r *postgresSystemLogRepository) DeleteOldLogs(ctx context.Context, days int) error {
	query := `DELETE FROM system_logs WHERE created_at < NOW() - INTERVAL '1 day' * $1`
	_, err := r.db.Exec(ctx, query, days)
	return err
}
