import { SendRequest } from '../components/Global/ApiRequest';

const getAllRole = async (queryParams) => {
    const response = await SendRequest({
        method: 'get',
        prefix: `roles/roles?${queryParams.toString()}`,
    });

    console.log('Role API Response:', response);

    // Parse query params to get page and limit
    const params = Object.fromEntries(queryParams);
    const currentPage = parseInt(params.page) || 1;
    const currentLimit = parseInt(params.limit) || 10;

    // Backend returns all data, so we need to do client-side pagination
    const allData = response.data || [];
    const totalData = allData.length;

    // Calculate start and end index for current page
    const startIndex = (currentPage - 1) * currentLimit;
    const endIndex = startIndex + currentLimit;

    // Slice data for current page
    const paginatedData = allData.slice(startIndex, endIndex);

    // Transform response to match TableList expected structure
    return {
        status: response.statusCode || 200,
        data: {
            data: paginatedData,
            paging: {
                page: currentPage,
                limit: currentLimit,
                total: totalData,
                page_total: Math.ceil(totalData / currentLimit),
            },
            total: totalData,
        },
    };
};

const getRoleById = async (id) => {
    const response = await SendRequest({
        method: 'get',
        prefix: `roles/roles/${id}`,
    });
    return response.data;
};

const createRole = async (queryParams) => {
    const response = await SendRequest({
        method: 'post',
        prefix: `roles/roles`,
        params: queryParams,
    });

    console.log('Create Role API Response:', response);

    // Check for error status (not 200, 201, or success)
    const isSuccess =
        response.statusCode === 200 || response.statusCode === 201 || response.status === 'success';

    if (!isSuccess && response.statusCode >= 400) {
        let errorMessage = response.message || 'Gagal menambahkan role';

        // Handle SQL unique constraint violation
        if (
            errorMessage.includes('UNIQUE KEY constraint') ||
            errorMessage.includes('duplicate key')
        ) {
            errorMessage = `Role dengan nama "${queryParams.role_name}" sudah ada. Silakan gunakan nama lain.`;
        }

        return {
            statusCode: response.statusCode,
            data: response.data,
            message: errorMessage,
        };
    }

    // Return full response with statusCode
    return {
        statusCode: response.statusCode || 200,
        data: response.data,
        message: response.message || 'Berhasil menambahkan role',
    };
};

const updateRole = async (role_id, queryParams) => {
    const response = await SendRequest({
        method: 'put',
        prefix: `roles/roles/${role_id}`,
        params: queryParams,
    });

    console.log('Update Role API Response:', response);

    // Check for error status (not 200, 201, or success)
    const isSuccess =
        response.statusCode === 200 || response.statusCode === 201 || response.status === 'success';

    if (!isSuccess && response.statusCode >= 400) {
        let errorMessage = response.message || 'Gagal mengubah role';

        // Handle SQL unique constraint violation
        if (
            errorMessage.includes('UNIQUE KEY constraint') ||
            errorMessage.includes('duplicate key')
        ) {
            errorMessage = `Role dengan nama "${queryParams.role_name}" sudah ada. Silakan gunakan nama lain.`;
        }

        return {
            statusCode: response.statusCode,
            data: response.data,
            message: errorMessage,
        };
    }

    // Return full response with statusCode
    return {
        statusCode: response.statusCode || 200,
        data: response.data,
        message: response.message || 'Berhasil mengubah role',
    };
};

const deleteRole = async (queryParams) => {
    const response = await SendRequest({
        method: 'delete',
        prefix: `roles/roles/${queryParams}`,
    });

    console.log('Delete API Response:', response);

    // Check for errors
    if (response.statusCode !== 200) {
        let errorMessage = response.message || 'Gagal menghapus role';

        // Handle foreign key constraint
        if (errorMessage.includes('REFERENCE constraint') || errorMessage.includes('foreign key')) {
            errorMessage = 'Role tidak dapat dihapus karena masih digunakan oleh user.';
        }

        return {
            statusCode: response.statusCode,
            data: response.data,
            message: errorMessage,
        };
    }

    // Return full response with statusCode
    return {
        statusCode: response.statusCode || 200,
        data: response.data,
        message: response.message,
    };
};

export { getAllRole, getRoleById, createRole, updateRole, deleteRole };
