<script setup lang="ts">
import { onUnmounted, ref } from "vue";
import { invoke } from "@tauri-apps/api/core";
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
import Terminal from "../Terminal.vue";
import Prompt from "../Prompt.vue";
import { useTerminal } from "../../composables/useTerminal";

interface Finding {
  param: string;
  location: string;
  technique: string;
  dbms?: string;
  prefix: string;
  suffix: string;
  payload: string;
  full_payload: string;
  evidence: string;
  confidence: string;
  extracted: Record<string, string>;
}

const url = ref("https://target.com/item.php?id=1");
const method = ref("GET");
const body = ref("");
const headersRaw = ref("");
const cookies = ref("");
const paramsFilter = ref("");

const tHeuristic = ref(true);
const tError = ref(true);
const tBoolean = ref(true);
const tUnion = ref(true);
const tTime = ref(false);

const level = ref(2);
const risk = ref(1);
const stopOnFirst = ref(true);
const autoExtract = ref(true);
const followRedirects = ref(true);

const tamperRandomcase = ref(false);
const tamperSpace2comment = ref(false);
const tamperEqualToLike = ref(false);

const concurrency = ref(4);
const timeoutMs = ref(15000);
const running = ref(false);
const findings = ref<Finding[]>([]);
const log = useTerminal();
const unlistens: UnlistenFn[] = [];

function parseHeaders(): Record<string, string> {
  const out: Record<string, string> = {};
  for (const line of headersRaw.value.split("\n")) {
    const i = line.indexOf(":");
    if (i === -1) continue;
    const k = line.slice(0, i).trim();
    const v = line.slice(i + 1).trim();
    if (k) out[k] = v;
  }
  return out;
}

async function run() {
  if (running.value) return;
  running.value = true;
  findings.value = [];
  log.clear();

  const techniques: string[] = [];
  if (tHeuristic.value) techniques.push("heuristic");
  if (tError.value) techniques.push("error");
  if (tBoolean.value) techniques.push("boolean");
  if (tUnion.value) techniques.push("union");
  if (tTime.value) techniques.push("time");
  if (!techniques.length) { log.err("pick at least one technique"); running.value = false; return; }

  const tamper: string[] = [];
  if (tamperRandomcase.value) tamper.push("randomcase");
  if (tamperSpace2comment.value) tamper.push("space2comment");
  if (tamperEqualToLike.value) tamper.push("equaltolike");

  const params = paramsFilter.value.split(/[\s,]+/).map(s => s.trim()).filter(Boolean);

  log.info(`target: ${method.value} ${url.value}`);
  log.info(`techniques: ${techniques.join(",")} | level=${level.value} risk=${risk.value} tamper=${tamper.join(",") || "none"}`);

  unlistens.push(await listen<string>("sqli:status", (e) => log.dim(String(e.payload))));
  unlistens.push(await listen<Finding>("sqli:hit", (e) => {
    const f = e.payload;
    findings.value.push(f);
    const dbms = f.dbms ? ` [DBMS:${f.dbms}]` : "";
    log.hit(`[${f.confidence}] ${f.technique}  ${f.location}:${f.param}${dbms}`);
    log.hit(`  payload:  ${f.full_payload}`);
    log.hit(`  evidence: ${f.evidence}`);
    for (const [k, v] of Object.entries(f.extracted)) {
      log.valid(`  ${k} = ${v}`);
    }
  }));

  try {
    await invoke("sqli_scan", {
      req: {
        url: url.value,
        method: method.value,
        body: body.value || null,
        headers: parseHeaders(),
        cookies: cookies.value || null,
        params: params.length ? params : null,
        techniques,
        level: level.value,
        risk: risk.value,
        stop_on_first: stopOnFirst.value,
        auto_extract: autoExtract.value,
        tamper,
        concurrency: concurrency.value,
        timeout_ms: timeoutMs.value,
        follow_redirects: followRedirects.value,
      },
    });
    log.ok(`scan done: ${findings.value.length} injection point(s)`);
  } catch (e: any) {
    log.err(String(e));
  } finally {
    running.value = false;
    cleanup();
  }
}

function cleanup() { while (unlistens.length) { const u = unlistens.pop(); if (u) u(); } }
onUnmounted(cleanup);
</script>

<template>
  <div class="module">
    <div class="form">
      <div class="row">
        <select v-model="method" class="method-sel">
          <option>GET</option>
          <option>POST</option>
          <option>PUT</option>
          <option>PATCH</option>
        </select>
        <input v-model="url" class="url-input" placeholder="https://target.com/item?id=1  (use * to mark injection point)" spellcheck="false" />
      </div>

      <details class="adv" open>
        <summary>request · body · cookies · headers</summary>
        <label class="ta">
          <span class="lbl">body (POST/PUT) · <code>*</code> marks injection point</span>
          <textarea class="term-input" v-model="body" rows="2" spellcheck="false" placeholder="user=admin&id=1*" />
        </label>
        <label class="ta">
          <span class="lbl">cookies · <code>*</code> marks injection point</span>
          <input class="inp" v-model="cookies" placeholder='sess=abc123; tracking=xxx*' />
        </label>
        <label class="ta">
          <span class="lbl">headers · <code>*</code> on value to inject there</span>
          <textarea class="term-input" v-model="headersRaw" rows="2" spellcheck="false" placeholder="Referer: https://x.com&#10;X-Forwarded-For: 1.2.3.4*" />
        </label>
        <Prompt label="params filter" v-model="paramsFilter" placeholder="id,cat (blank = test all)" />
      </details>

      <details class="adv">
        <summary>techniques</summary>
        <div class="row">
          <label class="toggle"><input type="checkbox" v-model="tHeuristic" /><span>heuristic</span></label>
          <label class="toggle"><input type="checkbox" v-model="tError" /><span>error</span></label>
          <label class="toggle"><input type="checkbox" v-model="tBoolean" /><span>bool-blind</span></label>
          <label class="toggle"><input type="checkbox" v-model="tUnion" /><span>union</span></label>
          <label class="toggle"><input type="checkbox" v-model="tTime" /><span>time-blind</span></label>
        </div>
      </details>

      <details class="adv">
        <summary>tuning · level / risk / tamper</summary>
        <div class="row">
          <label class="mini"><span>level</span><input v-model.number="level" type="number" min="1" max="3" /></label>
          <label class="mini"><span>risk</span><input v-model.number="risk" type="number" min="1" max="3" /></label>
          <label class="toggle"><input type="checkbox" v-model="stopOnFirst" /><span>stop first</span></label>
          <label class="toggle"><input type="checkbox" v-model="autoExtract" /><span>extract</span></label>
          <label class="toggle"><input type="checkbox" v-model="followRedirects" /><span>follow</span></label>
        </div>
        <div class="row">
          <span class="waf-label">tamper/WAF</span>
          <label class="toggle"><input type="checkbox" v-model="tamperRandomcase" /><span>randomcase</span></label>
          <label class="toggle"><input type="checkbox" v-model="tamperSpace2comment" /><span>space→/**/</span></label>
          <label class="toggle"><input type="checkbox" v-model="tamperEqualToLike" /><span>=→LIKE</span></label>
        </div>
      </details>

      <div class="row">
        <label class="mini"><span>conc</span><input v-model.number="concurrency" type="number" min="1" max="20" /></label>
        <label class="mini"><span>t/out</span><input v-model.number="timeoutMs" type="number" min="2000" max="60000" /></label>
      </div>

      <div class="row">
        <button class="exec" :disabled="running" @click="run">{{ running ? "[ injecting... ]" : "> inject" }}</button>
      </div>
    </div>

    <div v-if="findings.length" class="findings">
      <div v-for="(f, i) in findings" :key="i" class="finding" :class="`conf-${f.confidence.toLowerCase()}`">
        <div class="f-head">
          <span class="f-tech">{{ f.technique }}</span>
          <span class="f-loc">{{ f.location }} / <b>{{ f.param }}</b></span>
          <span v-if="f.dbms" class="f-dbms">{{ f.dbms }}</span>
          <span class="sev" :class="`sev-${f.confidence.toLowerCase()}`">{{ f.confidence }}</span>
        </div>
        <div class="f-payload">
          <span class="f-prefix" v-if="f.prefix">prefix <code>{{ f.prefix }}</code></span>
          <span class="f-suffix" v-if="f.suffix">suffix <code>{{ f.suffix }}</code></span>
        </div>
        <pre class="f-full">{{ f.full_payload }}</pre>
        <div class="f-evidence">» {{ f.evidence }}</div>
        <div v-if="Object.keys(f.extracted).length" class="f-extracted">
          <div v-for="(v, k) in f.extracted" :key="k" class="kv">
            <span class="k">{{ k }}:</span> <span class="v">{{ v }}</span>
          </div>
        </div>
      </div>
    </div>

    <Terminal :lines="log.lines.value" title="sqli // sqlmap-style detection" @clear="log.clear()" />
  </div>
</template>

<style scoped>
.adv { border: 1px solid var(--border); background: var(--bg-panel); padding: 4px 8px; }
.adv summary { cursor: pointer; font-size: 10px; color: var(--fg-dim); text-transform: uppercase; letter-spacing: 0.1em; padding: 2px 0; }
.adv summary:hover { color: var(--fg); }
.adv > *:not(summary) { margin-top: 6px; }

.method-sel {
  background: var(--bg-panel);
  border: 1px solid var(--alert);
  color: var(--alert);
  padding: 4px 8px;
  font-weight: 700;
  font-size: 12px;
  font-family: inherit;
  flex-shrink: 0;
}
.method-sel option { background: var(--bg); color: var(--fg); }
.url-input {
  flex: 1;
  background: var(--bg-panel);
  border: 1px solid var(--border);
  color: var(--fg);
  padding: 4px 8px;
  font-size: 12px;
  min-width: 0;
}
.url-input:focus { border-color: var(--accent); outline: none; }

.inp {
  background: var(--bg-panel);
  border: 1px solid var(--border);
  color: var(--fg);
  padding: 4px 8px;
  font-size: 12px;
  font-family: inherit;
  width: 100%;
}
.inp:focus { border-color: var(--info); outline: none; }

code {
  color: var(--info);
  background: var(--bg);
  padding: 0 4px;
  border: 1px solid var(--border);
  font-size: 10px;
}
.waf-label {
  color: var(--warn);
  font-size: 10px;
  text-transform: uppercase;
  letter-spacing: 0.15em;
  align-self: center;
  padding-right: 4px;
}

.findings { display: flex; flex-direction: column; gap: 6px; max-height: 300px; overflow-y: auto; }
.finding {
  background: var(--bg-panel);
  border: 1px solid var(--border);
  padding: 6px 8px;
  display: flex;
  flex-direction: column;
  gap: 3px;
}
.finding.conf-high { border-left: 3px solid var(--alert); }
.finding.conf-medium { border-left: 3px solid var(--warn); }
.finding.conf-low { border-left: 3px solid var(--fg-dim); }
.f-head { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; font-size: 11px; }
.f-tech {
  font-weight: 700;
  color: var(--alert);
  text-transform: uppercase;
  letter-spacing: 0.1em;
  font-size: 10px;
}
.f-loc { color: var(--info); font-size: 11px; }
.f-loc b { color: var(--fg); }
.f-dbms { color: var(--valid); font-size: 10px; border: 1px solid var(--valid); padding: 0 5px; }
.f-payload { display: flex; gap: 8px; font-size: 10px; color: var(--fg-dim); flex-wrap: wrap; }
.f-full {
  background: var(--bg);
  border: 1px solid var(--border);
  padding: 4px 6px;
  font-size: 11px;
  color: var(--valid);
  white-space: pre-wrap;
  word-break: break-all;
  font-family: var(--mono);
  margin: 0;
}
.f-evidence { color: var(--fg-dim); font-size: 10px; font-style: italic; }
.f-extracted {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  gap: 3px;
  margin-top: 3px;
}
.kv {
  background: var(--bg);
  border: 1px solid var(--border);
  padding: 2px 6px;
  font-size: 10px;
}
.kv .k { color: var(--fg-dim); text-transform: uppercase; letter-spacing: 0.1em; font-size: 9px; }
.kv .v { color: var(--valid); font-weight: 700; }
</style>
