const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const { v4: uuid } = require('uuid');
const { pgPool } = require('../config/services');
const env = require('../config/env');
const logger = require('../utils/logger');

const USERS_TABLE = 'users';

const ensureUserTable = async () => {
  const createTableSQL = `
    CREATE TABLE IF NOT EXISTS ${USERS_TABLE} (
      id VARCHAR(36) PRIMARY KEY,
      email VARCHAR(255) UNIQUE NOT NULL,
      password_hash TEXT NOT NULL,
      created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
    );
  `;

  await pgPool.query(createTableSQL);
  logger.info('👥 Kullanici tablosu hazir');
};

const hashPassword = (plain) => bcrypt.hash(plain, 10);
const comparePassword = (plain, hash) => bcrypt.compare(plain, hash);

const createUser = async ({ email, password }) => {
  const existing = await findUserByEmail(email);
  if (existing) {
    const error = new Error('Bu email ile kayitli kullanici zaten var');
    error.status = 409;
    throw error;
  }
  const passwordHash = await hashPassword(password);
  const id = uuid();
  await pgPool.query(
    `INSERT INTO ${USERS_TABLE} (id, email, password_hash) VALUES ($1, $2, $3)`,
    [id, email, passwordHash]
  );
  return { id, email };
};

const findUserByEmail = async (email) => {
  const { rows } = await pgPool.query(
    `SELECT id, email, password_hash FROM ${USERS_TABLE} WHERE email=$1 LIMIT 1`,
    [email]
  );
  return rows[0] || null;
};

const generateToken = (payload) =>
  jwt.sign(payload, env.jwt.secret, { expiresIn: env.jwt.expiresIn });

const validateCredentials = async ({ email, password }) => {
  const user = await findUserByEmail(email);
  if (!user) {
    const error = new Error('Giris bilgileri hatali');
    error.status = 401;
    throw error;
  }
  const isValid = await comparePassword(password, user.password_hash);
  if (!isValid) {
    const error = new Error('Giris bilgileri hatali');
    error.status = 401;
    throw error;
  }
  return { id: user.id, email: user.email };
};

const buildAuthResponse = (user) => ({
  token: generateToken({ sub: user.id, email: user.email }),
  user
});

module.exports = {
  ensureUserTable,
  createUser,
  validateCredentials,
  buildAuthResponse
};
