import Mapping from '../models/mapping.js';
import Login from '../models/login.js';
import Treelogy from '../models/treelogy.js';
import { successResponse, errorResponse } from '../utils/response.js';

export async function createMapping(req, res) {
  try {
    const {
      login_id,
      treelogy_id,
      description,
      code,
      role,
      view_permission,
      profile = 0,
      status = 1,
      created_by = 0,
      sort_order = 0,
      current_map_year = 0
    } = req.body;

    if (!login_id || !treelogy_id || !description || !code || !role || !view_permission) {
      return errorResponse(res, 400, 'Missing required fields');
    }

    const [login, tree] = await Promise.all([
      Login.findByPk(login_id),
      Treelogy.findByPk(treelogy_id),
    ]);
    if (!login) return errorResponse(res, 404, 'Login not found');
    if (!tree) return errorResponse(res, 404, 'Treelogy not found');

    const mapping = await Mapping.create({
      login_id,
      treelogy_id,
      description,
      code,
      role,
      view_permission,
      profile,
      status,
      created_by,
      sort_order,
      current_map_year
    });

    return successResponse(res, 201, 'Mapping created successfully', mapping);
  } catch (error) {
    return errorResponse(res, 500, 'Error creating mapping', error.message);
  }
}
