package sqlite

import (
	"context"
	"database/sql"
	"encoding/base64"

	"chat-switchboard/models"

	"github.com/google/uuid"
)

// GitCredentialStore implements store.GitCredentialStore for SQLite.
type GitCredentialStore struct{}

func (s *GitCredentialStore) Create(ctx context.Context, cred *models.GitCredential) error {
	if cred.ID == "" {
		cred.ID = uuid.NewString()
	}
	_, err := DB.ExecContext(ctx, `
		INSERT INTO git_credentials (id, user_id, name, auth_type, encrypted_data, nonce, public_key, fingerprint, persona_id, created_at)
		VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))`,
		cred.ID, cred.UserID, cred.Name, cred.AuthType,
		base64.StdEncoding.EncodeToString(cred.EncryptedData),
		base64.StdEncoding.EncodeToString(cred.Nonce),
		cred.PublicKey, cred.Fingerprint, cred.PersonaID,
	)
	if err != nil {
		return err
	}
	// Read back created_at
	return DB.QueryRowContext(ctx,
		`SELECT created_at FROM git_credentials WHERE id = ?`, cred.ID,
	).Scan(st(&cred.CreatedAt))
}

func (s *GitCredentialStore) GetByID(ctx context.Context, id string) (*models.GitCredential, error) {
	var c models.GitCredential
	var encData, nonce string
	err := DB.QueryRowContext(ctx, `
		SELECT id, user_id, name, auth_type, encrypted_data, nonce, public_key, fingerprint, persona_id, created_at
		FROM git_credentials WHERE id = ?`, id,
	).Scan(&c.ID, &c.UserID, &c.Name, &c.AuthType,
		&encData, &nonce, &c.PublicKey, &c.Fingerprint, &c.PersonaID, st(&c.CreatedAt))
	if err != nil {
		return nil, err
	}
	c.EncryptedData, _ = base64.StdEncoding.DecodeString(encData)
	c.Nonce, _ = base64.StdEncoding.DecodeString(nonce)
	return &c, nil
}

func (s *GitCredentialStore) ListByUser(ctx context.Context, userID string) ([]models.GitCredential, error) {
	rows, err := DB.QueryContext(ctx, `
		SELECT id, user_id, name, auth_type, encrypted_data, nonce, public_key, fingerprint, persona_id, created_at
		FROM git_credentials WHERE user_id = ? ORDER BY created_at DESC`, userID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var creds []models.GitCredential
	for rows.Next() {
		var c models.GitCredential
		var encData, nonce string
		if err := rows.Scan(&c.ID, &c.UserID, &c.Name, &c.AuthType,
			&encData, &nonce, &c.PublicKey, &c.Fingerprint, &c.PersonaID, st(&c.CreatedAt)); err != nil {
			return nil, err
		}
		c.EncryptedData, _ = base64.StdEncoding.DecodeString(encData)
		c.Nonce, _ = base64.StdEncoding.DecodeString(nonce)
		creds = append(creds, c)
	}
	return creds, rows.Err()
}

func (s *GitCredentialStore) Delete(ctx context.Context, id, userID string) error {
	res, err := DB.ExecContext(ctx, `DELETE FROM git_credentials WHERE id = ? AND user_id = ?`, id, userID)
	if err != nil {
		return err
	}
	n, _ := res.RowsAffected()
	if n == 0 {
		return sql.ErrNoRows
	}
	return nil
}
