package models

import (
	"time"

	"mengpost-backend/database"
)

// SentLog 记录一次外发邮件的结果.
type SentLog struct {
	ID        int64     `json:"id"`
	AccountID int64     `json:"account_id"`
	To        string    `json:"to"`
	Subject   string    `json:"subject"`
	Body      string    `json:"body"`
	Status    string    `json:"status"`
	Error     string    `json:"error"`
	CreatedAt time.Time `json:"created_at"`
}

func AddSentLog(l *SentLog) error {
	_, err := database.DB.Exec(
		`INSERT INTO sent_logs(account_id,to_addr,subject,body,status,error) VALUES(?,?,?,?,?,?)`,
		l.AccountID, l.To, l.Subject, l.Body, l.Status, l.Error,
	)
	return err
}

func ListSentLogs(accountID int64, limit int) ([]SentLog, error) {
	if limit <= 0 {
		limit = 50
	}
	rows, err := database.DB.Query(
		`SELECT id,account_id,to_addr,subject,body,status,error,created_at FROM sent_logs WHERE account_id=? ORDER BY id DESC LIMIT ?`,
		accountID, limit,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []SentLog
	for rows.Next() {
		var l SentLog
		if err := rows.Scan(&l.ID, &l.AccountID, &l.To, &l.Subject, &l.Body, &l.Status, &l.Error, &l.CreatedAt); err != nil {
			return nil, err
		}
		out = append(out, l)
	}
	return out, nil
}
