using Microsoft.Data.Sqlite;
using Project.Model;
namespace Project.Persistence;

public partial class SQLite
{
    //filepath for home-pc:
    private static string _dbPath = "C:/Users/Soi/Desktop/keywi.db";
    //filepath for work-laptop:
    //private static string _dbPath = "C:/Users/lowns/Desktop/keywi.db";
    //KLASSENVARIABLEN ERSTELLEN
    //private static string loginname;
    
    
    //checks if there is a sqlite database in _dbPath on programm startup, if not -> creates the database and a table LOGINS
    public static void Init()
    {
        using var connection = new SqliteConnection($"Data Source={_dbPath}");
        connection.Open();

        var command = connection.CreateCommand();
        command.CommandText =
            @"
            CREATE TABLE IF NOT EXISTS LOGINS (
                loginname STRING PRIMARY KEY NOT NULL,
                loginpass STRING NOT NULL,
                loginemail STRING NOT NULL
            );
        ";
        command.ExecuteNonQuery();
        command.CommandText =
            @"
            CREATE TABLE IF NOT EXISTS SAVED_LOGINS (
                name STRING PRIMARY KEY NOT NULL,
                pass STRING NOT NULL,
                mail_username STRING NOT NULL,
                note STRING,
                owner STRING NOT NULL,
                FOREIGN KEY(owner) REFERENCES LOGINS(loginname)

            );
        ";
        command.ExecuteNonQuery();
    }
    
    //saves a new user to the table LOGINS
    public static void SaveUser(NewUser user)
    {
        using var connection = new SqliteConnection($"Data Source={_dbPath}");
        connection.Open();
        using (var command = connection.CreateCommand())
        {
            command.Parameters.AddWithValue("@loginname", user.NewLoginName);
            command.Parameters.AddWithValue("@loginpass", user.NewMasterPassword);
            command.Parameters.AddWithValue("@loginemail", user.NewEmail);
            
            command.CommandText =
            @"
            INSERT INTO LOGINS (loginname, loginpass, loginemail)
            VALUES (@loginname, @loginpass, @loginemail);";
            command.ExecuteNonQuery();
            
        }
    }
}