export default class ProjectsDataSource {

    constructor({ api, endpoint, pageSize = 10 }) {

        this.api = api;
        this.endpoint = endpoint;

        this.pageSize = pageSize;
        this.currentPage = 1;

        this.totalPages = 1;
        this.totalRecords = 0;

        this.records = [];
        this.searchTerm = "";

        this.onDataLoaded = null;
        this.onError = null;
    }

    async loadPage(page = 1) {

        this.currentPage = page;

        const params = {
            page: this.currentPage,
            size: this.pageSize,
            search: this.searchTerm.trim()
        };

        try {

            const response = await this.api.get(this.endpoint, params);

            const records = response?.data ?? [];
            const total = response?.pagination?.total ?? records.length;

            this.records = records;
            this.totalRecords = total;

            this.totalPages = Math.max(
                1,
                Math.ceil(this.totalRecords / this.pageSize)
            );

            if (this.onDataLoaded) {

                this.onDataLoaded({
                    records: this.records,
                    currentPage: this.currentPage,
                    totalPages: this.totalPages,
                    totalRecords: this.totalRecords
                });

            }

        } catch (err) {

            console.error("[ProjectsDataSource] Fetch Error:", err);

            this.records = [];
            this.totalPages = 1;
            this.totalRecords = 0;

            if (this.onError) {
                this.onError(err);
            }

        }

    }

    setSearch(term) {

        this.searchTerm = term || "";
        this.loadPage(1);

    }

    reload() {

        this.loadPage(this.currentPage);

    }

    updateRecord(id, data) {

        const idx = this.records.findIndex(
            r => String(r.id) === String(id)
        );

        if (idx !== -1) {
            this.records[idx] = { ...this.records[idx], ...data };
        }

    }

    deleteRecord(id) {

        this.records = this.records.filter(
            r => String(r.id) !== String(id)
        );

    }

    destroy() {

        this.records = [];

    }

}
