<script setup lang="ts">
import {getMarketTypes, TaxInput, useMarketTaxStore} from "@/market";
import {BuyModal} from '@/market/acquisition';
import {ScanResult, ScanResultTable, toScanResult} from '@/market/scan';
import {marketApi} from "@/mammon";
import {useStorage} from "@vueuse/core";
import {ref, watch} from 'vue';

const buyModal = ref<typeof BuyModal>();

const marketTaxStore = useMarketTaxStore();
const days = useStorage('market-scan-days', 365);
const items = ref<ScanResult[]>([]);
const loading = ref(false);

const scan = async () => {
    loading.value = true;
    try {
        const { data } = await marketApi.scanMarket(
            days.value,
            marketTaxStore.brokerFee / 100,
            marketTaxStore.scc / 100
        );
        const types = await getMarketTypes(data.map(r => r.marketTypeId));

        items.value = data.flatMap(r => {
            const type = types.find(t => t.id === r.marketTypeId);

            return type ? [toScanResult(r, type)] : [];
        });
    } finally {
        loading.value = false;
    }
}

watch([days, () => marketTaxStore.brokerFee, () => marketTaxStore.scc], scan, { immediate: true });
</script>

<template>
    <div class="flex mb-2 mt-4">
        <div class="flex justify-self-end ms-auto">
            <TaxInput />
            <div class="end">
                <span>Days: </span>
                <input type="number" min="1" max="365" step="1" v-model="days" />
            </div>
        </div>
    </div>
    <hr />
    <div v-if="loading" class="text-center mt-4">
        <span>Scanning market…</span>
    </div>
    <template v-else>
        <ScanResultTable :items="items" @buy="(type, buy, sell) => buyModal?.open(type, { 'Buy': buy, 'Sell': sell })" />
        <BuyModal ref="buyModal" />
    </template>
</template>

<style scoped>
@reference "@/style.css";
div.end {
    @apply justify-self-end ms-2;
}
</style>
