package db

import (
	"database/sql"
	"fmt"

	"git.faercol.me/faercol/polyculeconnect/polyculeconnect/config"
	"git.faercol.me/faercol/polyculeconnect/polyculeconnect/internal/db/authcode"
	"git.faercol.me/faercol/polyculeconnect/polyculeconnect/internal/db/authrequest"
	"git.faercol.me/faercol/polyculeconnect/polyculeconnect/internal/db/backend"
	"git.faercol.me/faercol/polyculeconnect/polyculeconnect/internal/db/client"
)

type Storage interface {
	DB() *sql.DB
	ClientStorage() client.ClientDB
	BackendStorage() backend.BackendDB
	AuthRequestStorage() authrequest.AuthRequestDB
	AuthCodeStorage() authcode.AuthCodeDB
}

type sqlStorage struct {
	db *sql.DB
}

func (s *sqlStorage) DB() *sql.DB {
	return s.db
}

func (s *sqlStorage) ClientStorage() client.ClientDB {
	return client.New(s.db)
}

func (s *sqlStorage) BackendStorage() backend.BackendDB {
	return backend.New(s.db)
}

func (s *sqlStorage) AuthRequestStorage() authrequest.AuthRequestDB {
	return authrequest.New(s.db)
}

func (s *sqlStorage) AuthCodeStorage() authcode.AuthCodeDB {
	return authcode.New(s.db)
}

func New(conf config.AppConfig) (Storage, error) {
	db, err := sql.Open("sqlite3", conf.StorageConfig.File)
	if err != nil {
		return nil, fmt.Errorf("failed to open DB: %w", err)
	}
	return &sqlStorage{db: db}, nil
}
