package com.example.myapplication6;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;

/**
 * Simple local user storage for login/signup (demo-grade, device-local).
 */
public class AuthDb extends SQLiteOpenHelper {

    private static final String DB_NAME = "AuthDB";
    private static final int DB_VERSION = 1;
    private static final String TABLE_USERS = "users";

    public AuthDb(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(
                "CREATE TABLE " + TABLE_USERS + " (" +
                        "username TEXT PRIMARY KEY, " +
                        "salt TEXT NOT NULL, " +
                        "password_hash TEXT NOT NULL" +
                        ")");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // No-op for now; bumping DB_VERSION will recreate in a more complete app.
    }

    public boolean createUser(String username, String password) {
        String u = normalize(username);
        if (u == null) return false;
        if (password == null || password.isEmpty()) return false;

        byte[] saltBytes = new byte[16];
        new SecureRandom().nextBytes(saltBytes);
        String saltHex = toHex(saltBytes);
        String hashHex = sha256Hex(saltHex + ":" + password);

        SQLiteDatabase db = getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("username", u);
        values.put("salt", saltHex);
        values.put("password_hash", hashHex);

        try {
            db.insertOrThrow(TABLE_USERS, null, values);
            return true;
        } catch (Exception e) {
            return false; // Likely already exists.
        } finally {
            db.close();
        }
    }

    public boolean verifyUser(String username, String password) {
        String u = normalize(username);
        if (u == null) return false;
        if (password == null) return false;

        SQLiteDatabase db = getReadableDatabase();
        Cursor c = null;
        try {
            c = db.query(
                    TABLE_USERS,
                    new String[] {"salt", "password_hash"},
                    "username=?",
                    new String[] {u},
                    null,
                    null,
                    null
            );

            if (!c.moveToFirst()) return false;
            String saltHex = c.getString(0);
            String storedHash = c.getString(1);
            String computed = sha256Hex(saltHex + ":" + password);
            return computed.equalsIgnoreCase(storedHash);
        } finally {
            if (c != null) c.close();
            db.close();
        }
    }

    private static String normalize(String username) {
        if (username == null) return null;
        String u = username.trim();
        if (u.isEmpty()) return null;
        if (u.length() < 3) return null;
        return u;
    }

    private static String sha256Hex(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] bytes = digest.digest(input.getBytes(StandardCharsets.UTF_8));
            return toHex(bytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String toHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        for (byte b : bytes) sb.append(String.format("%02x", b));
        return sb.toString();
    }
}

