import apiClient from './authApi';

export interface WorkflowTemplate {
    id: string;
    name: string;
    description: string;
    category: string;
    priority: 'low' | 'medium' | 'high';
    estimatedTime: string;
    approvers: any[];
    suggestedSLA: number;
    isActive: boolean;
    fields?: any;
}

// Simple in-memory cache
let templatesCache: WorkflowTemplate[] | null = null;

export const getCachedTemplates = () => templatesCache;

export const createTemplate = async (templateData: Partial<WorkflowTemplate>): Promise<WorkflowTemplate> => {
    const response = await apiClient.post('/templates', templateData);
    const t = response.data.data;

    // Map backend response
    const mappedTemplate = {
        id: t.templateId || t.id,
        name: t.templateName || t.name,
        description: t.templateDescription || t.description,
        category: t.templateCategory || t.category,
        priority: t.priority || 'medium',
        estimatedTime: t.estimatedTime || 'Variable',
        approvers: t.approvalLevelsConfig || t.approvers || [],
        suggestedSLA: t.defaultTatHours || t.suggestedSLA || 24,
        isActive: t.isActive,
        fields: t.userFieldMappings || t.fields
    };

    // Invalidate cache or add to it
    if (templatesCache) templatesCache.push(mappedTemplate as WorkflowTemplate);
    return mappedTemplate as WorkflowTemplate;
};

export const getTemplates = async (): Promise<WorkflowTemplate[]> => {
    const response = await apiClient.get('/templates');
    const data = response.data?.data || [];

    // Map backend response to frontend interface
    const mappedData = data.map((t: any) => ({
        id: t.templateId || t.id,
        name: t.templateName || t.name,
        description: t.templateDescription || t.description,
        category: t.templateCategory || t.category,
        priority: t.priority || 'medium', // Default if missing
        estimatedTime: t.estimatedTime || 'Variable',
        approvers: t.approvalLevelsConfig || t.approvers || [],
        suggestedSLA: t.defaultTatHours || t.suggestedSLA || 24,
        isActive: t.isActive,
        fields: t.userFieldMappings || t.fields
    }));

    templatesCache = mappedData;
    return mappedData;
};

export const deleteTemplate = async (id: string): Promise<void> => {
    await apiClient.delete(`/templates/${id}`);
    if (templatesCache) {
        templatesCache = templatesCache.filter(t => t.id !== id);
    }
};

export const updateTemplate = async (id: string, templateData: Partial<WorkflowTemplate>): Promise<WorkflowTemplate> => {
    const response = await apiClient.put(`/templates/${id}`, templateData);
    const t = response.data.data;

    // Map backend response
    const mappedTemplate = {
        id: t.templateId || t.id,
        name: t.templateName || t.name,
        description: t.templateDescription || t.description,
        category: t.templateCategory || t.category,
        priority: t.priority || 'medium',
        estimatedTime: t.estimatedTime || 'Variable',
        approvers: t.approvalLevelsConfig || t.approvers || [],
        suggestedSLA: t.defaultTatHours || t.suggestedSLA || 24,
        isActive: t.isActive,
        fields: t.userFieldMappings || t.fields
    };

    if (templatesCache) {
        templatesCache = templatesCache.map(cacheItem => cacheItem.id === id ? (mappedTemplate as WorkflowTemplate) : cacheItem);
    }
    return mappedTemplate as WorkflowTemplate;
};
