package store

import (
	"database/sql"
	"errors"
	"fmt"

	"github.com/google/uuid"
)

// CreateInstance inserts a new instance record.
func (s *Store) CreateInstance(inst Instance) (Instance, error) {
	inst.ID = uuid.New().String()
	inst.CreatedAt = now()
	inst.UpdatedAt = inst.CreatedAt

	_, err := s.db.Exec(
		`INSERT INTO instances (id, stage_id, project_id, container_id, image_tag, subdomain, npm_proxy_id, status, port, created_at, updated_at)
		 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
		inst.ID, inst.StageID, inst.ProjectID, inst.ContainerID, inst.ImageTag,
		inst.Subdomain, inst.NpmProxyID, inst.Status, inst.Port, inst.CreatedAt, inst.UpdatedAt,
	)
	if err != nil {
		return Instance{}, fmt.Errorf("insert instance: %w", err)
	}
	return inst, nil
}

// CreateInstanceWithID inserts a new instance using a pre-generated ID.
// Use this when the ID must be known before creation (e.g., for container labels).
func (s *Store) CreateInstanceWithID(inst Instance) (Instance, error) {
	if inst.ID == "" {
		return Instance{}, fmt.Errorf("instance ID is required")
	}
	inst.CreatedAt = now()
	inst.UpdatedAt = inst.CreatedAt

	_, err := s.db.Exec(
		`INSERT INTO instances (id, stage_id, project_id, container_id, image_tag, subdomain, npm_proxy_id, status, port, created_at, updated_at)
		 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
		inst.ID, inst.StageID, inst.ProjectID, inst.ContainerID, inst.ImageTag,
		inst.Subdomain, inst.NpmProxyID, inst.Status, inst.Port, inst.CreatedAt, inst.UpdatedAt,
	)
	if err != nil {
		return Instance{}, fmt.Errorf("insert instance: %w", err)
	}
	return inst, nil
}

// GetInstanceByID returns a single instance by its ID.
func (s *Store) GetInstanceByID(id string) (Instance, error) {
	var inst Instance
	err := s.db.QueryRow(
		`SELECT id, stage_id, project_id, container_id, image_tag, subdomain, npm_proxy_id, status, port, created_at, updated_at
		 FROM instances WHERE id = ?`, id,
	).Scan(&inst.ID, &inst.StageID, &inst.ProjectID, &inst.ContainerID, &inst.ImageTag,
		&inst.Subdomain, &inst.NpmProxyID, &inst.Status, &inst.Port, &inst.CreatedAt, &inst.UpdatedAt)
	if errors.Is(err, sql.ErrNoRows) {
		return Instance{}, fmt.Errorf("instance %s: %w", id, ErrNotFound)
	}
	if err != nil {
		return Instance{}, fmt.Errorf("query instance: %w", err)
	}
	return inst, nil
}

// GetInstancesByStageID returns all instances for a given stage.
func (s *Store) GetInstancesByStageID(stageID string) ([]Instance, error) {
	rows, err := s.db.Query(
		`SELECT id, stage_id, project_id, container_id, image_tag, subdomain, npm_proxy_id, status, port, created_at, updated_at
		 FROM instances WHERE stage_id = ? ORDER BY created_at DESC`, stageID,
	)
	if err != nil {
		return nil, fmt.Errorf("query instances: %w", err)
	}
	defer rows.Close()

	var instances []Instance
	for rows.Next() {
		var inst Instance
		if err := rows.Scan(&inst.ID, &inst.StageID, &inst.ProjectID, &inst.ContainerID, &inst.ImageTag,
			&inst.Subdomain, &inst.NpmProxyID, &inst.Status, &inst.Port, &inst.CreatedAt, &inst.UpdatedAt); err != nil {
			return nil, fmt.Errorf("scan instance: %w", err)
		}
		instances = append(instances, inst)
	}
	return instances, rows.Err()
}

// UpdateInstance updates an existing instance's mutable fields.
func (s *Store) UpdateInstance(inst Instance) error {
	inst.UpdatedAt = now()
	result, err := s.db.Exec(
		`UPDATE instances SET stage_id=?, project_id=?, container_id=?, image_tag=?, subdomain=?, npm_proxy_id=?, status=?, port=?, updated_at=?
		 WHERE id=?`,
		inst.StageID, inst.ProjectID, inst.ContainerID, inst.ImageTag,
		inst.Subdomain, inst.NpmProxyID, inst.Status, inst.Port, inst.UpdatedAt, inst.ID,
	)
	if err != nil {
		return fmt.Errorf("update instance: %w", err)
	}
	n, _ := result.RowsAffected()
	if n == 0 {
		return fmt.Errorf("instance %s: %w", inst.ID, ErrNotFound)
	}
	return nil
}

// UpdateInstanceStatus sets only the status field on an instance.
func (s *Store) UpdateInstanceStatus(id string, status string) error {
	ts := now()
	result, err := s.db.Exec(
		`UPDATE instances SET status=?, updated_at=? WHERE id=?`,
		status, ts, id,
	)
	if err != nil {
		return fmt.Errorf("update instance status: %w", err)
	}
	n, _ := result.RowsAffected()
	if n == 0 {
		return fmt.Errorf("instance %s: %w", id, ErrNotFound)
	}
	return nil
}

// DeleteInstance removes an instance by ID.
func (s *Store) DeleteInstance(id string) error {
	result, err := s.db.Exec(`DELETE FROM instances WHERE id = ?`, id)
	if err != nil {
		return fmt.Errorf("delete instance: %w", err)
	}
	n, _ := result.RowsAffected()
	if n == 0 {
		return fmt.Errorf("instance %s: %w", id, ErrNotFound)
	}
	return nil
}
