package main

import (
	"database/sql"
	"fmt"
	"log"

	_ "github.com/go-sql-driver/mysql"
)

func main() {
	// MySQL connection info
	username := "root"
	password := "root"
	hostname := "127.0.0.1"
	port := "3306"
	dbname := "nl_blog"

	// Build DSN
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", username, password, hostname, port, dbname)

	// Connect to MySQL
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		log.Fatalf("Failed to open database connection: %v", err)
	}
	defer db.Close()

	// Create table query
	createTableQuery := `
		CREATE TABLE IF NOT EXISTS user_access_logs (
			id INT AUTO_INCREMENT PRIMARY KEY,
			user_id INT DEFAULT 0 COMMENT '用户ID（未登录用户为0）',
			user_ip VARCHAR(45) NOT NULL COMMENT '用户IP地址',
			user_location VARCHAR(100) COMMENT '用户归属地',
			article_id INT NOT NULL COMMENT '访问的文章ID',
			access_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '访问时间',
			INDEX idx_user_id (user_id),
			INDEX idx_article_id (article_id),
			INDEX idx_access_time (access_time)
		) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户访问记录表';
	`

	// Execute query
	_, err = db.Exec(createTableQuery)
	if err != nil {
		log.Fatalf("Failed to create table: %v", err)
	}

	fmt.Println("Table 'user_access_logs' created successfully (or already exists).")
}
