package model

import (
	"crawler/config"
	"crawler/service"
)

type AccessLogInterface interface {
	Save()
}

type AccessLogModel struct {
	AccessLog
}

type AccessLog struct {
	RequestID    string `json:"request_id"`
	RequestURI   string `json:"request_uri"`
	ClientIP     string `json:"client_ip"`
	Referer      string `json:"referer"`
	UserAgent    string `json:"useragent"`
	Browser      string `json:"browser"`
	Os           string `json:"os"`
	Device       string `json:"device"`
	Method       string `json:"method"`
	ErrorMessage string `json:"error_message"`
	Latency      string `json:"latency"`
	Status       int    `json:"status"`
	CreatedAt    string `json:"created_at"`
}

// 접속기록
func (this *AccessLogModel) Save() {
	var (
		db   = service.DB_CRAWLER
		conn = db.SQLDB
	)

	sql := `
		INSERT INTO tb_access_log
		SET 
			request_id = ?, 
			request_uri = ?, 
			client_ip = ?, 
			referer = ?,
			useragent = ?, 
			browser = ?, 
			os = ?, 
			device = ?, 
			method = ?, 
			error_message = ?, 
			latency = ?, 
			status = ?, 
			created_at = NOW();
	`
	_, err := conn.Exec(sql,
		this.RequestID, this.RequestURI, this.ClientIP, this.Referer,
		this.UserAgent, this.Browser, this.Os, this.Device, this.Method,
		this.ErrorMessage, this.Latency, this.Status,
	)
	if err != nil {
		db.SetErrorLog(err, sql)
	}

	db.SetGeneralLog(config.GL_ACTION_WRITE, sql, "insert access log")
}
