package device

import (
	"database/sql"
	"time"
)

// MySQLStorage MySQL设备存储

type MySQLStorage struct {
	db *sql.DB
}

// NewMySQLStorage 创建MySQL设备存储实例
func NewMySQLStorage(db *sql.DB) (*MySQLStorage, error) {
	// 创建表
	if err := createDeviceTable(db); err != nil {
		return nil, err
	}
	return &MySQLStorage{db: db}, nil
}

// createDeviceTable 创建设备表
func createDeviceTable(db *sql.DB) error {
	query := `
	CREATE TABLE IF NOT EXISTS devices (
		id VARCHAR(64) PRIMARY KEY,
		name VARCHAR(128) NOT NULL,
		ip VARCHAR(64),
		token VARCHAR(64) NOT NULL,
		status VARCHAR(32) NOT NULL DEFAULT 'inactive',
		created_at BIGINT NOT NULL,
		updated_at BIGINT NOT NULL,
		UNIQUE KEY uk_token (token)
	) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
	`
	_, err := db.Exec(query)
	return err
}

// GetDevices 获取所有设备
func (s *MySQLStorage) GetDevices() []Device {
	query := "SELECT id, name, ip, token, status, created_at, updated_at FROM devices"
	rows, err := s.db.Query(query)
	if err != nil {
		return []Device{}
	}
	defer rows.Close()

	devices := make([]Device, 0)
	for rows.Next() {
		var device Device
		var createdAt, updatedAt int64
		if err := rows.Scan(&device.ID, &device.Name, &device.IP, &device.Token, &device.Status, &createdAt, &updatedAt); err != nil {
			continue
		}
		device.CreatedAt = createdAt
		device.UpdatedAt = updatedAt
		devices = append(devices, device)
	}

	return devices
}

// GetDevice 获取指定设备
func (s *MySQLStorage) GetDevice(id string) (Device, bool) {
	query := "SELECT id, name, ip, token, status, created_at, updated_at FROM devices WHERE id = ?"
	row := s.db.QueryRow(query, id)

	var device Device
	var createdAt, updatedAt int64
	err := row.Scan(&device.ID, &device.Name, &device.IP, &device.Token, &device.Status, &createdAt, &updatedAt)
	if err != nil {
		return Device{}, false
	}
	device.CreatedAt = createdAt
	device.UpdatedAt = updatedAt

	return device, true
}

// GetDeviceByToken 通过令牌获取设备
func (s *MySQLStorage) GetDeviceByToken(token string) (Device, bool) {
	query := "SELECT id, name, ip, token, status, created_at, updated_at FROM devices WHERE token = ?"
	row := s.db.QueryRow(query, token)

	var device Device
	var createdAt, updatedAt int64

	err := row.Scan(&device.ID, &device.Name, &device.IP, &device.Token, &device.Status, &createdAt, &updatedAt)
	if err != nil {
		return Device{}, false
	}

	device.CreatedAt = createdAt
	device.UpdatedAt = updatedAt

	return device, true
}

// AddDevice 添加设备
func (s *MySQLStorage) AddDevice(device Device) error {
	query := "INSERT INTO devices (id, name, ip, token, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE name = VALUES(name), ip = VALUES(ip), updated_at = VALUES(updated_at)"
	_, err := s.db.Exec(query, device.ID, device.Name, device.IP, device.Token, device.Status, device.CreatedAt, device.UpdatedAt)
	return err
}

// UpdateDevice 更新设备
func (s *MySQLStorage) UpdateDevice(device Device) error {
	query := "UPDATE devices SET name = ?, ip = ?, status = ?, updated_at = ? WHERE id = ?"
	_, err := s.db.Exec(query, device.Name, device.IP, device.Status, device.UpdatedAt, device.ID)
	return err
}

// DeleteDevice 删除设备
func (s *MySQLStorage) DeleteDevice(id string) error {
	query := "DELETE FROM devices WHERE id = ?"
	_, err := s.db.Exec(query, id)
	return err
}

// UpdateDeviceStatus 更新设备状态
func (s *MySQLStorage) UpdateDeviceStatus(id string, status string) error {
	query := "UPDATE devices SET status = ?, updated_at = ? WHERE id = ?"
	_, err := s.db.Exec(query, status, time.Now().Unix(), id)
	return err
}
