<script setup>
import { ref } from "vue";
import { q, m, useAsyncData, useQuasar } from "#imports";
const $q = useQuasar();
const { data: system, refresh } = await useAsyncData("database-check", async () => {
  const result = await q({
    system: {
      database: {
        checkResult: true
      }
    }
  });
  return result.system;
});
const expanded = ref([]);
const tableColumns = [
  { name: "table", label: "Table", field: "table", align: "left" },
  { name: "status", label: "Status", field: "status", align: "center" },
  { name: "count", label: "Differences", field: (row) => row.differences.length, align: "center" },
  { name: "action", label: "Action", field: "action", align: "center" }
];
const diffColumns = [
  { name: "type", label: "Type", field: "type", align: "left" },
  { name: "column", label: "Column", field: "column", align: "left" },
  { name: "details", label: "Details", field: "details", align: "left" }
];
const getStatusColor = (status) => status === "OK" ? "positive" : "warning";
const getDiffDetails = (diff) => {
  if (diff.type === "missing_column") {
    return `Missing: ${diff.expected.name} (${diff.expected.type})`;
  }
  if (diff.type === "extra_column") {
    return `Extra: ${diff.current.type}${diff.current.length ? `(${diff.current.length})` : ""}`;
  }
  if (diff.type === "column_mismatch") {
    return Object.entries(diff.differences).map(([key, val]) => `${key}: ${JSON.stringify(val)}`).join(" | ");
  }
  if (diff.current) {
    return JSON.stringify(diff.current).substring(0, 100) + "...";
  }
  return "";
};
const getDiffTypeColor = (type) => {
  switch (type) {
    case "missing_column":
      return "negative";
    case "extra_column":
      return "info";
    case "column_mismatch":
      return "warning";
    default:
      return "grey";
  }
};
const toggleExpanded = (tableName) => {
  const index = expanded.value.indexOf(tableName);
  if (index === -1) {
    expanded.value.push(tableName);
  } else {
    expanded.value.splice(index, 1);
  }
};
const handleFix = async (tableName) => {
  $q.dialog({
    title: "Confirm Fix",
    message: `Are you sure you want to fix the table "${tableName}"? This action cannot be undone.`,
    cancel: true,
    persistent: true
  }).onOk(async () => {
    await m("fixDatabaseTable", { name: tableName });
    await refresh();
  });
};
</script>

<template>
    <l-page>

        <div class="q-mb-md">
            <h5 class="q-ma-none">Database Check Results</h5>
        </div>

        <q-table :rows="system.database.checkResult" :columns="tableColumns" row-key="table" flat bordered
            class="q-mb-lg" v-model:expanded="expanded" :pagination.sync="{ rowsPerPage: 0 }" hide-bottom>
            <template #body="props">
                <q-tr :props="props"
                    :class="{ 'bg-red-1': props.row.status === 'DIFFERENT', 'bg-green-1': props.row.status === 'OK' }">
                    <q-td auto-width>
                        <q-btn size="sm" flat dense round
                            :icon="expanded.includes(props.row.table) ? 'expand_less' : 'expand_more'"
                            @click="toggleExpanded(props.row.table)" />
                    </q-td>
                    <q-td key="table" :props="props" class="text-weight-bold">
                        {{ props.row.table }}
                    </q-td>
                    <q-td key="status" :props="props">
                        <q-chip :label="props.row.status" :color="getStatusColor(props.row.status)" text-color="white"
                            size="sm" />
                    </q-td>
                    <q-td key="count" :props="props">
                        <q-chip v-if="props.row.differences.length > 0" :label="props.row.differences.length"
                            color="warning" text-color="white" size="sm" />
                        <span v-else class="text-positive">✓</span>
                    </q-td>
                    <q-td key="action" :props="props">
                        <q-btn v-if="props.row.status !== 'OK'" label="Fix" size="sm" color="primary"
                            @click="handleFix(props.row.table)" />
                    </q-td>
                </q-tr>

                <!-- Differences Details Expansion -->
                <q-tr v-show="expanded.includes(props.row.table)" :props="props">
                    <q-td colspan="100%" class="q-pa-none">
                        <div class="q-pa-md bg-grey-1">
                            <q-table v-if="props.row.differences.length > 0" :rows="props.row.differences"
                                :columns="diffColumns" row-key="column" flat dense class="q-mb-md"
                                :pagination.sync="{ rowsPerPage: 0 }" hide-bottom>
                                <template #body-cell-type="cellProps">
                                    <q-td :props="cellProps">
                                        <q-chip :label="cellProps.row.type"
                                            :color="getDiffTypeColor(cellProps.row.type)" text-color="white"
                                            size="sm" />
                                    </q-td>
                                </template>
                                <template #body-cell-details="cellProps">
                                    <q-td :props="cellProps">
                                        <q-expansion-item header-class="text-caption" expand-icon-class="text-caption"
                                            dense>
                                            <template #header>
                                                <span class="text-caption">{{ getDiffDetails(cellProps.row) }}</span>
                                            </template>
                                            <pre class="q-ma-none text-caption">{{
                                                JSON.stringify(cellProps.row.differences || cellProps.row.current ||
                                                    cellProps.row.expected, null,
                                                    2) }}
                                            </pre>
                                        </q-expansion-item>
                                    </q-td>
                                </template>
                            </q-table>
                            <div v-else class="text-positive text-weight-bold">✓ No Differences</div>
                        </div>
                    </q-td>
                </q-tr>
            </template>
        </q-table>

    </l-page>
</template>
