import request from '../utils/request';

const API_URL = '/{{ model.module_name }}s';

export interface {{ model.name }} {
{% for field in model.fields %}
    {% if 'r' in field.permissions %}
    {{ field.name }}: {{ 'string' if 'str' in field.type else 'number' if 'int' in field.type or 'float' in field.type else 'boolean' if 'bool' in field.type else 'any' }};
    {% endif %}
{% endfor %}
}

export interface PaginatedResponse<T> {
    items: T[];
    total: number;
    page: number;
    size: number;
    total_pages: number;
}

export const get{{ model.name }}s = async (page = 1, size = 20, query?: string) => {
    let url = `${API_URL}/?page=${page}&size=${size}`;
    if (query) {
        url += `&q=${encodeURIComponent(query)}`;
    }
    const response = await request.get<PaginatedResponse<{{ model.name }}>>(url);
    return response.data;
};

export const get{{ model.name }} = async (id: number) => {
    const response = await request.get<{{ model.name }}>(`${API_URL}/${id}`);
    return response.data;
};

export const create{{ model.name }} = async (data: any) => {
    const response = await request.post<{{ model.name }}>(`${API_URL}/`, data);
    return response.data;
};

export const update{{ model.name }} = async (id: number, data: any) => {
    const response = await request.put<{{ model.name }}>(`${API_URL}/${id}`, data);
    return response.data;
};

export const delete{{ model.name }} = async (id: number) => {
    const response = await request.delete<{{ model.name }}>(`${API_URL}/${id}`);
    return response.data;
};

{% if model.m2m_fields %}
{% for m2m in model.m2m_fields %}
import { {{ m2m.target_model }} } from './{{ m2m.target_model.lower() }}';
export const get{{ model.name }}{{ m2m.target_model }}s = async (id: number, page = 1, size = 20) => {
    const response = await request.get<PaginatedResponse<{{ m2m.target_model }}>>(`${API_URL}/${id}/{{ m2m.name }}?page=${page}&size=${size}`);
    return response.data;
};
{% endfor %}
{% endif %}
