import {fetchWithToken} from "./repo.ts";
import type {SchematicCode, SchematicInfo, SchematicList} from "../types/schem.ts";
import {SchematicCodeSchema, SchematicInfoSchema, SchematicListSchema} from "../types/schem.ts";

export class SchematicRepo {
    constructor(private token: string) {}

    public async getRootSchematicList(): Promise<SchematicList> {
        return await fetchWithToken(this.token, "/schem").then(value => value.json()).then(SchematicListSchema.parse);
    }

    public async getSchematicList(id: number): Promise<SchematicList> {
        return await fetchWithToken(this.token, `/schem/${id}/list`).then(value => value.json()).then(SchematicListSchema.parse);
    }

    public async getSchematicInfo(id: number): Promise<SchematicInfo> {
        return await fetchWithToken(this.token, `/schem/${id}`).then(value => value.json()).then(SchematicInfoSchema.parse);
    }

    public async createDownload(id: number): Promise<SchematicCode> {
        return await fetchWithToken(this.token, `/schem/${id}/download`).then(value => value.json()).then(SchematicCodeSchema.parse);
    }

    public async uploadSchematic(name: string, content: string) {
        return await fetchWithToken(this.token, `/schem`, {
            method: "POST",
            body: JSON.stringify({
                name,
                content
            })
        })
    }
}