// index.js
import express from "express";
import cors from "cors";
import mysql from "mysql2";

const app = express();
app.use(cors());
app.use(express.json());

// ======== DATABASE CONNECTION ========
const db = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",  
  database: "bank310" 
});

db.connect(err => {
  if (err) {
    console.error("Database connection failed:", err);
  } else {
    console.log("✅ Connected to MySQL");
  }
});



// Get all accounts
app.get("/accounts", (req, res) => {
  db.query("SELECT AccountID, Username, Name, Surname, CreatedAt FROM Account", (err, result) => {
    if (err) return res.status(500).json(err);
    res.json(result);
  });
});

// Get all balances
app.get("/balances", (req, res) => {
  db.query("SELECT * FROM Balance", (err, result) => {
    if (err) return res.status(500).json(err);
    res.json(result);
  });
});

// Get single balance
app.get("/balance/:accountId", (req, res) => {
  db.query("SELECT * FROM Balance WHERE AccountID = ?", [req.params.accountId], (err, result) => {
    if (err) return res.status(500).json(err);
    res.json(result[0] || { message: "Account not found" });
  });
});

// Send money (create transaction)
app.post("/transfer", (req, res) => {
  const { senderId, receiverId, amount, comment } = req.body;

  if (!senderId || !receiverId || !amount)
    return res.status(400).json({ error: "Missing fields" });

  db.beginTransaction(err => {
    if (err) return res.status(500).json(err);

    // 1. Check sender balance
    db.query("SELECT Balance FROM Balance WHERE BankAccountID = ?", [senderId], (err, senderResult) => {
      if (err || senderResult.length === 0)
        return db.rollback(() => res.status(400).json({ error: "Invalid sender" }));

      const senderBalance = senderResult[0].Balance;
      if (senderBalance < amount)
        return db.rollback(() => res.status(400).json({ error: "Insufficient funds" }));

      // 2. Deduct from sender, add to receiver
      db.query("UPDATE Balance SET Balance = Balance - ? WHERE BankAccountID = ?", [amount, senderId]);
      db.query("UPDATE Balance SET Balance = Balance + ? WHERE BankAccountID = ?", [amount, receiverId]);

      // 3. Insert transaction
      const txId = `${senderId}_${receiverId}_${Date.now()}`;
      const sql = "INSERT INTO Transactions (TransactionID, SenderBankAccountID, ReceiverBankAccountID, Amount, Comment) VALUES (?, ?, ?, ?, ?)";
      db.query(sql, [txId, senderId, receiverId, amount, comment || null], err => {
        if (err)
          return db.rollback(() => res.status(500).json(err));

        // 4. Insert into Logs (optional if trigger not used)
        db.query("INSERT INTO Logs (Action, Description) VALUES (?, ?)", [
          "Transaction",
          `${senderId} sent ${amount} to ${receiverId}: ${comment || "No comment"}`
        ]);

        // 5. Commit transaction
        db.commit(err => {
          if (err)
            return db.rollback(() => res.status(500).json(err));

          res.json({ success: true, transactionId: txId });
        });
      });
    });
  });
});

// Get all transactions
app.get("/transactions", (req, res) => {
  db.query("SELECT * FROM Transactions ORDER BY Timestamp DESC", (err, result) => {
    if (err) return res.status(500).json(err);
    res.json(result);
  });
});

// Get logs
app.get("/logs", (req, res) => {
  db.query("SELECT * FROM Logs ORDER BY CreatedAt DESC", (err, result) => {
    if (err) return res.status(500).json(err);
    res.json(result);
  });
});

// ======== START SERVER ========
const PORT = 3000;
app.listen(PORT, () => console.log(`🚀 Bank API running on http://localhost:${PORT}`));

import bcrypt from "bcrypt";

// ===============================
// REGISTER
// ===============================
app.post("/register", async (req, res) => {
  const { username, password, name, surname } = req.body;

  if (!username || !password || !name || !surname)
    return res.status(400).json({ error: "Missing fields" });

  try {
    // hash password
    const hash = await bcrypt.hash(password, 10);

    // insert user
    db.query(
      "INSERT INTO Account (Username, PasswordHash, Name, Surname) VALUES (?, ?, ?, ?)",
      [username, hash, name, surname],
      (err, result) => {
        if (err) {
          if (err.code === "ER_DUP_ENTRY")
            return res.status(400).json({ error: "Username already exists" });
          return res.status(500).json(err);
        }

        const accountId = result.insertId;
        const bankAccountId = accountId + 100;

        // create balance row for new user
        db.query(
          "INSERT INTO Balance (AccountID, BankAccountID, Balance) VALUES (?, ?, ?)",
          [accountId, bankAccountId, 0],
          (err2) => {
            if (err2) return res.status(500).json(err2);
            res.json({ success: true, message: "Account created", accountId, bankAccountId });
          }
        );
      }
    );
  } catch (err) {
    res.status(500).json({ error: "Server error" });
  }
});

// ===============================
// LOGIN
// ===============================
app.post("/login", (req, res) => {
  const { username, password } = req.body;

  if (!username || !password)
    return res.status(400).json({ error: "Missing username or password" });

  db.query("SELECT * FROM Account WHERE Username = ?", [username], async (err, users) => {
    if (err) return res.status(500).json(err);
    if (users.length === 0) return res.status(400).json({ error: "User not found" });

    const user = users[0];
    const valid = await bcrypt.compare(password, user.PasswordHash);

    if (!valid) return res.status(401).json({ error: "Invalid password" });

    res.json({
      success: true,
      accountId: user.AccountID,
      username: user.Username,
      name: user.Name,
      surname: user.Surname
    });
  });
});
