package db

import (
	"database/sql"
	"errors"
)

// SenderWithDomain joins a Sender with its Domain's name, mirroring the
// Sender+Domain join used by senders.py's list view.
type SenderWithDomain struct {
	Sender
	DomainName string
}

func (d *DB) ListSenders() ([]SenderWithDomain, error) {
	rows, err := d.Query(`SELECT s.id, s.email, s.password_hash, s.domain_id, s.can_send_as_domain, s.is_active, s.created_at, s.store_message_content, dm.domain_name
		FROM esrv_senders s JOIN esrv_domains dm ON dm.id = s.domain_id ORDER BY s.email`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []SenderWithDomain
	for rows.Next() {
		var s SenderWithDomain
		var createdAt string
		if err := rows.Scan(&s.ID, &s.Email, &s.PasswordHash, &s.DomainID, &s.CanSendAsDomain, &s.IsActive, &createdAt, &s.StoreMessageContent, &s.DomainName); err != nil {
			return nil, err
		}
		s.CreatedAt, _ = parseTime(createdAt)
		out = append(out, s)
	}
	return out, rows.Err()
}

func (d *DB) GetSenderByID(id int64) (*Sender, error) {
	row := d.QueryRow(`SELECT id, email, password_hash, domain_id, can_send_as_domain, is_active, created_at, store_message_content
		FROM esrv_senders WHERE id = ?`, id)
	var s Sender
	var createdAt string
	if err := row.Scan(&s.ID, &s.Email, &s.PasswordHash, &s.DomainID, &s.CanSendAsDomain, &s.IsActive, &createdAt, &s.StoreMessageContent); err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			return nil, nil
		}
		return nil, err
	}
	s.CreatedAt, _ = parseTime(createdAt)
	return &s, nil
}

func (d *DB) CountActiveSenders() (int, error) {
	var n int
	err := d.QueryRow(`SELECT COUNT(*) FROM esrv_senders WHERE is_active = 1`).Scan(&n)
	return n, err
}

func (d *DB) EmailExists(email string, excludeID int64) (bool, error) {
	var n int
	err := d.QueryRow(`SELECT COUNT(*) FROM esrv_senders WHERE lower(email) = lower(?) AND id != ?`, email, excludeID).Scan(&n)
	return n > 0, err
}

func (d *DB) CreateSender(email, passwordHash string, domainID int64, canSendAsDomain, storeMessageContent bool) (int64, error) {
	res, err := d.Exec(`INSERT INTO esrv_senders (email, password_hash, domain_id, can_send_as_domain, is_active, store_message_content)
		VALUES (?, ?, ?, ?, 1, ?)`, email, passwordHash, domainID, canSendAsDomain, storeMessageContent)
	if err != nil {
		return 0, err
	}
	return res.LastInsertId()
}

func (d *DB) UpdateSender(id int64, email, passwordHash string, domainID int64, canSendAsDomain, storeMessageContent bool) error {
	if passwordHash == "" {
		_, err := d.Exec(`UPDATE esrv_senders SET email = ?, domain_id = ?, can_send_as_domain = ?, store_message_content = ? WHERE id = ?`,
			email, domainID, canSendAsDomain, storeMessageContent, id)
		return err
	}
	_, err := d.Exec(`UPDATE esrv_senders SET email = ?, password_hash = ?, domain_id = ?, can_send_as_domain = ?, store_message_content = ? WHERE id = ?`,
		email, passwordHash, domainID, canSendAsDomain, storeMessageContent, id)
	return err
}

func (d *DB) SetSenderActive(id int64, active bool) error {
	_, err := d.Exec(`UPDATE esrv_senders SET is_active = ? WHERE id = ?`, active, id)
	return err
}

func (d *DB) RemoveSender(id int64) error {
	_, err := d.Exec(`DELETE FROM esrv_senders WHERE id = ?`, id)
	return err
}
