<!--
|--------------------------------------------------------------------------
| DevDatabaseTab.vue — comandos do db.cjs via copy-to-clipboard
|--------------------------------------------------------------------------
-->
<script setup>
import { ref, onMounted } from 'vue';
import { supabase } from '@/lib/supabase/client';
import { useToast } from 'primevue/usetoast';
import { logError } from '@/support/supportLogger';

const toast = useToast();
const recentLogs = ref([]);

const commands = [
    {
        group: 'Operação diária',
        items: [
            {
                label: 'Backup completo',
                cmd: 'cd database-novo && node db.cjs backup',
                desc: 'Gera schema.sql + data.sql + full_dump.sql + supabase_restore.sql em backups/YYYY-MM-DD/',
                icon: 'pi-save'
            },
            {
                label: 'Status do banco',
                cmd: 'cd database-novo && node db.cjs status',
                desc: 'Mostra estado: container rodando, último backup, migrations aplicadas, contagens',
                icon: 'pi-chart-bar'
            },
            {
                label: 'Verify (integridade)',
                cmd: 'cd database-novo && node db.cjs verify',
                desc: 'Checa tabelas e views essenciais (definidas em db.config.json → verify)',
                icon: 'pi-check-circle'
            }
        ]
    },
    {
        group: 'Dashboards e exports',
        items: [
            {
                label: 'Gerar dashboard HTML do banco',
                cmd: 'cd database-novo && node db.cjs dashboard',
                desc: 'Regenera agenciapsi-db-dashboard.html com domínios + infraestrutura + busca',
                icon: 'pi-th-large'
            },
            {
                label: 'Schema export (00_full..10_grants)',
                cmd: 'cd database-novo && node db.cjs schema-export',
                desc: 'Atualiza as 11 pastas schema/ a partir do estado atual do banco',
                icon: 'pi-file-export'
            },
            {
                label: 'Diff vs último backup',
                cmd: 'cd database-novo && node db.cjs diff',
                desc: 'Lista tabelas novas, alteradas e removidas desde o último backup',
                icon: 'pi-compare'
            }
        ]
    },
    {
        group: 'Migrations e seeds',
        items: [
            {
                label: 'Aplicar migrations pendentes',
                cmd: 'cd database-novo && node db.cjs migrate',
                desc: 'Aplica migrations em database-novo/migrations/ ainda não aplicadas. Faz backup antes.',
                icon: 'pi-forward'
            },
            {
                label: 'Rodar todos os seeds',
                cmd: 'cd database-novo && node db.cjs seed all',
                desc: 'Roda seeds dos grupos users + system',
                icon: 'pi-database'
            },
            {
                label: 'Seed: system (inclui dev_*)',
                cmd: 'cd database-novo && node db.cjs seed system',
                desc: 'Popula tabelas do sistema (planos, features, templates + dev_phases/items/auditoria/competitors)',
                icon: 'pi-cog'
            }
        ]
    },
    {
        group: 'Operações críticas',
        items: [
            {
                label: 'Restore (último backup)',
                cmd: 'cd database-novo && node db.cjs restore',
                desc: 'Restaura do backup mais recente. Prioriza supabase_restore.sql.',
                icon: 'pi-history',
                danger: true
            },
            {
                label: 'Reset (DROP + setup)',
                cmd: 'cd database-novo && node db.cjs reset',
                desc: 'DROP schema public + reinstala tudo. Faz backup antes.',
                icon: 'pi-refresh',
                danger: true
            },
            {
                label: 'Setup do zero',
                cmd: 'cd database-novo && node db.cjs setup',
                desc: 'Primeira instalação: schema + fixes + seeds + migrations + backup + verify',
                icon: 'pi-bolt',
                danger: true
            }
        ]
    }
];

async function loadLogs() {
    try {
        const { data } = await supabase
            .from('dev_generation_log')
            .select('*')
            .order('created_at', { ascending: false })
            .limit(10);
        recentLogs.value = data || [];
    } catch (e) {
        logError('DevDatabaseTab', 'loadRecentLogs', e);
    }
}

async function copyToClipboard(cmd) {
    try {
        await navigator.clipboard.writeText(cmd);
        toast.add({
            severity: 'success',
            summary: 'Copiado!',
            detail: 'Cole no terminal e execute.',
            life: 2500
        });
    } catch (e) {
        toast.add({
            severity: 'error',
            summary: 'Falha ao copiar',
            detail: 'Copie manualmente — clipboard indisponível.',
            life: 4000
        });
    }
}

function formatDate(iso) {
    if (!iso) return '—';
    return new Date(iso).toLocaleString('pt-BR');
}

onMounted(loadLogs);
</script>

<template>
    <div class="db-tab">
        <div class="notice">
            <i class="pi pi-info-circle" />
            <div>
                <strong>Copy-to-clipboard mode.</strong>
                Os comandos precisam ser executados no terminal (na raiz do projeto). Na Parte C futuro vai ter um CLI server local que executa direto daqui.
                <br />
                <span class="text-[var(--text-color-secondary)]">
                    O container Supabase precisa estar rodando (<code>npx supabase start</code>) antes de qualquer comando.
                </span>
            </div>
        </div>

        <div v-for="group in commands" :key="group.group" class="cmd-group">
            <h3 class="cmd-group-title">{{ group.group }}</h3>
            <div class="cmd-list">
                <article v-for="cmd in group.items" :key="cmd.label" :class="['cmd-card', { danger: cmd.danger }]">
                    <div class="cmd-head">
                        <div class="cmd-icon">
                            <i :class="['pi', cmd.icon]" />
                        </div>
                        <div class="cmd-title-wrap">
                            <h4 class="cmd-title">
                                {{ cmd.label }}
                                <span v-if="cmd.danger" class="danger-chip">CUIDADO</span>
                            </h4>
                            <p class="cmd-desc">{{ cmd.desc }}</p>
                        </div>
                    </div>
                    <div class="cmd-action">
                        <code class="cmd-text">{{ cmd.cmd }}</code>
                        <button class="cmd-copy" @click="copyToClipboard(cmd.cmd)">
                            <i class="pi pi-copy" /> Copiar
                        </button>
                    </div>
                </article>
            </div>
        </div>

        <!-- Histórico -->
        <div class="cmd-group">
            <h3 class="cmd-group-title">Últimas execuções registradas</h3>
            <div v-if="!recentLogs.length" class="empty">Nenhum log ainda.</div>
            <ul v-else class="log-list">
                <li v-for="log in recentLogs" :key="log.id" class="log-item">
                    <i
                        :class="['pi', log.sucesso ? 'pi-check-circle' : 'pi-times-circle']"
                        :style="{ color: log.sucesso ? '#10b981' : '#ef4444' }"
                    />
                    <span class="log-tipo">{{ log.tipo }}</span>
                    <span class="log-cmd">{{ log.comando || '—' }}</span>
                    <span class="log-date">{{ formatDate(log.created_at) }}</span>
                </li>
            </ul>
        </div>
    </div>
</template>

<style scoped>
.db-tab { display: flex; flex-direction: column; gap: 14px; }

.notice {
    display: flex;
    gap: 10px;
    align-items: flex-start;
    background: color-mix(in srgb, var(--primary-color) 6%, transparent);
    border: 1px solid color-mix(in srgb, var(--primary-color) 20%, transparent);
    border-radius: 10px;
    padding: 12px 14px;
    font-size: 12px;
    color: var(--text-color);
}
.notice i { color: var(--primary-color); font-size: 16px; flex-shrink: 0; margin-top: 1px; }
.notice strong { color: var(--primary-color); }
.notice code { font-family: 'IBM Plex Mono', monospace; font-size: 11px; }

.cmd-group {
    background: var(--surface-card, #fff);
    border: 1px solid var(--surface-border);
    border-radius: 10px;
    padding: 14px;
}

.cmd-group-title {
    font-size: 12px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    color: var(--text-color-secondary);
    margin-bottom: 10px;
    padding-bottom: 8px;
    border-bottom: 1px solid var(--surface-border);
}

.cmd-list { display: flex; flex-direction: column; gap: 10px; }

.cmd-card {
    background: var(--surface-ground, #f8fafc);
    border: 1px solid var(--surface-border);
    border-radius: 8px;
    padding: 12px;
    transition: border-color 0.15s;
}
.cmd-card:hover { border-color: color-mix(in srgb, var(--primary-color) 30%, var(--surface-border)); }
.cmd-card.danger { border-left: 3px solid #ef4444; }

.cmd-head { display: flex; gap: 10px; margin-bottom: 8px; }
.cmd-icon {
    display: grid;
    place-items: center;
    width: 32px;
    height: 32px;
    border-radius: 7px;
    background: color-mix(in srgb, var(--primary-color) 10%, transparent);
    color: var(--primary-color);
    font-size: 14px;
    flex-shrink: 0;
}

.cmd-card.danger .cmd-icon {
    background: rgba(239,68,68,.1);
    color: #ef4444;
}

.cmd-title-wrap { flex: 1; min-width: 0; }

.cmd-title {
    font-size: 13px;
    font-weight: 600;
    color: var(--text-color);
    margin: 0;
    display: flex;
    align-items: center;
    gap: 8px;
}
.danger-chip {
    font-size: 9px;
    font-weight: 700;
    color: #ef4444;
    background: rgba(239,68,68,.1);
    padding: 2px 6px;
    border-radius: 4px;
    letter-spacing: 0.3px;
}

.cmd-desc {
    font-size: 11px;
    color: var(--text-color-secondary);
    line-height: 1.5;
    margin: 3px 0 0;
}

.cmd-action {
    display: flex;
    align-items: center;
    gap: 8px;
    background: #0b0d12;
    border-radius: 6px;
    padding: 6px 10px;
}

.cmd-text {
    flex: 1;
    font-family: 'IBM Plex Mono', 'Menlo', 'Monaco', monospace;
    font-size: 11px;
    color: #e2e8f8;
    white-space: nowrap;
    overflow-x: auto;
    padding: 2px 0;
}

.cmd-copy {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    background: var(--primary-color);
    color: white;
    border: none;
    border-radius: 5px;
    padding: 5px 10px;
    font-size: 11px;
    font-weight: 600;
    cursor: pointer;
    transition: opacity 0.15s;
    flex-shrink: 0;
}
.cmd-copy:hover { opacity: 0.9; }
.cmd-copy:active { transform: scale(0.97); }

.log-list { list-style: none; margin: 0; padding: 0; }
.log-item {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 7px 0;
    font-size: 12px;
    border-bottom: 1px solid var(--surface-border);
}
.log-item:last-child { border-bottom: none; }
.log-tipo {
    font-weight: 600;
    font-family: 'IBM Plex Mono', monospace;
    font-size: 10px;
    text-transform: uppercase;
    padding: 2px 7px;
    background: color-mix(in srgb, var(--primary-color) 10%, transparent);
    color: var(--primary-color);
    border-radius: 4px;
}
.log-cmd {
    font-family: 'IBM Plex Mono', monospace;
    color: var(--text-color-secondary);
    font-size: 11px;
    flex: 1;
    min-width: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.log-date { font-size: 11px; color: var(--text-color-secondary); }

.empty {
    text-align: center;
    padding: 20px;
    color: var(--text-color-secondary);
    font-size: 12px;
}
</style>
