import bcrypt from 'bcryptjs';
import Login from '../models/login.js';
import Client from '../models/client.js';
import { successResponse, errorResponse } from '../utils/response.js';
import { getRoleNames } from '../middleware/auth.js';

export async function initSuperAdmin(req, res) {
  try {
    // Get role names dynamically
    const roleNames = await getRoleNames();
    const SUPER_ADMIN = roleNames.find(name => name === 'SUPER_ADMIN');
    
    if (!SUPER_ADMIN) {
      return errorResponse(res, 500, 'SUPER_ADMIN role not found in database');
    }

    const count = await Login.count({ where: { role_name: SUPER_ADMIN } });
    if (count > 0) {
      return errorResponse(res, 409, 'Super Admin already initialized');
    }
    const { name, member_id, mobile_number, password } = req.body || {};
    if (!name || !password || (!member_id && !mobile_number)) {
      return errorResponse(res, 400, 'name, password and member_id or mobile_number are required');
    }
    
    // Get the SUPER_ADMIN role ID
    const { UserMaster } = require('../models/index.js');
    const superAdminRole = await UserMaster.findOne({ where: { role_name: SUPER_ADMIN } });
    if (!superAdminRole) {
      return errorResponse(res, 500, 'SUPER_ADMIN role not found in UserMaster table');
    }

    const hash = await bcrypt.hash(password, 10);
    const sa = await Login.create({
      // Super Admin is global: client_id and treelogy_id can be null
      client_id: null,
      treelogy_id: null,
      member_id: member_id || null,
      mobile_number: mobile_number || null,
      password: hash,
      role_id: superAdminRole.id,
      name,
      status: 'Y',
      security_no: '0',
      com_id: 10,
    });
    return successResponse(res, 201, 'Super Admin initialized', { id: sa.login_id, name: sa.name });
  } catch (e) {
    return errorResponse(res, 500, 'Error initializing Super Admin', e.message);
  }
}

export async function createClientAsSuperAdmin(req, res) {
  try {
    // Only SUPER_ADMIN should access this route (enforced by middleware)
    const { client_name, mobile, landline = '', email = '', address = '', details = '', status = 1 } = req.body || {};
    if (!client_name) return errorResponse(res, 400, 'client_name is required');

    const client = await Client.create({ client_name, mobile, landline, email, address, details, status });
    return successResponse(res, 201, 'Client created', client);
  } catch (e) {
    return errorResponse(res, 500, 'Error creating client', e.message);
  }
}