import{j as e}from"./vendor-codemirror-CkItnc0H.js";import{r as a,f as Y,h as Z}from"./vendor-ui-BLV2MnSs.js";import{M as ee,S as C,I as z,B as U,c as te}from"./index-CsURyoH0.js";import"./vendor-ag-grid-NsbaVf01.js";function _(l){return l==null?"NULL":typeof l=="number"||typeof l=="bigint"?String(l):`'${String(l).split("'").join("''")}'`}function k(l,v,f,n,r,d){if(l==="csv"){const{delimiter:i,quoteChar:s,escapeChar:u,lineTerminator:m}=d,w=h=>{const x=h==null?"":String(h);return s&&(x.includes(i)||x.includes(s)||x.includes(`
`))?s+x.split(s).join(u+s)+s:x},E=[n.columns.map(h=>s?s+h+s:h).join(i),...n.rows.map(h=>h.map(w).join(i))].join(m);return d.encoding==="utf-8-sig"?"\uFEFF"+E:E}if(l==="insert"){const i=n.columns.map(u=>`\`${u}\``).join(", "),s=n.rows.map(u=>`(${u.map(_).join(", ")})`).join(`,
`);return`INSERT INTO \`${v}\`.\`${f}\` (${i}) VALUES
${s};
`}const j=r.length>0?r:n.columns,p=n.rows.map(i=>{const s=j.map(u=>{const m=n.columns.indexOf(u);return`\`${u}\` = ${_(m>=0?i[m]:null)}`}).join(" AND ");return`DELETE FROM \`${v}\`.\`${f}\` WHERE ${s};`}).join(`
`);if(l==="delete")return p+`
`;const S=n.columns.map(i=>`\`${i}\``).join(", "),c=n.rows.map(i=>`(${i.map(_).join(", ")})`).join(`,
`);return p+`

INSERT INTO \`${v}\`.\`${f}\` (${S}) VALUES
${c};
`}function ae({open:l,onClose:v,sessionId:f,database:n,table:r,sql:d,pkValues:j,rowsOverride:p,pkColumnsForSql:S=[]}){const[c,i]=a.useState(d?"csv":"insert"),[s,u]=a.useState("500"),[m,w]=a.useState(!1),[$,E]=a.useState(!1),[h,x]=a.useState(!1),[b,q]=a.useState(!1),[y,P]=a.useState(","),[I,H]=a.useState(""),[L,W]=a.useState('"'),[T,J]=a.useState('"'),[M,V]=a.useState("crlf"),[N,X]=a.useState("utf-8"),Q={crlf:`\r
`,lf:`
`,cr:"\r"}[M]||`\r
`,B=y==="custom"?I:y,D=()=>JSON.stringify({database:n,...d?{sql:d}:{table:r},format:c,batch_size:parseInt(s),...j?{pk_values:j}:{},...c==="csv"?{csv_delimiter:B,csv_quotechar:L,csv_escapechar:T,csv_lineterminator:Q,csv_encoding:N}:{}}),A=()=>({delimiter:B,quoteChar:L,escapeChar:T,lineTerminator:Q,encoding:N}),G=async()=>{w(!0);try{let t,o;if(p){const g=k(c,n,r,p,S,A());t=new Blob([g],{type:"text/plain;charset=utf-8"}),o=`${n}_${r}_filtered.${c==="csv"?"csv":"sql"}`}else{const g=await fetch(`/api/v1/sessions/${f}/export`,{method:"POST",headers:{"Content-Type":"application/json"},body:D()});if(!g.ok)throw new Error(await g.text());t=await g.blob();const O=(g.headers.get("Content-Disposition")??"").match(/filename="([^"]+)"/);o=O?O[1]:`${n}_${r}.${c==="csv"?"csv":"sql"}`}const R=URL.createObjectURL(t),F=document.createElement("a");F.download=o,F.href=R,F.click(),URL.revokeObjectURL(R),v()}catch(t){alert(`Export failed: ${t}`)}finally{w(!1)}},K=async()=>{E(!0);try{let t;if(p)t=k(c,n,r,p,S,A());else if(window.isSecureContext){const o=await fetch(`/api/v1/sessions/${f}/export`,{method:"POST",headers:{"Content-Type":"application/json"},body:D()});if(!o.ok)throw new Error(await o.text());t=await(await o.blob()).text()}else{const o=new XMLHttpRequest;if(o.open("POST",`/api/v1/sessions/${f}/export`,!1),o.setRequestHeader("Content-Type","application/json"),o.send(D()),o.status!==200)throw new Error(o.responseText);t=o.responseText}await te(t),x(!0),setTimeout(()=>x(!1),1500)}catch(t){alert(`Copy failed: ${t}`)}finally{E(!1)}};return e.jsx(ee,{open:l,onClose:v,title:`Export ${n}.${r}`,footer:e.jsxs(e.Fragment,{children:[e.jsx(U,{variant:"ghost",onClick:v,children:"Cancel"}),e.jsx(U,{variant:"ghost",onClick:K,disabled:$||m,children:h?"Copied! ✓":$?"Copying…":"Copy"}),e.jsx(U,{variant:"primary",onClick:G,disabled:m||$,children:m?"Exporting…":"Download"})]}),children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs(C,{label:"Format",value:c,onChange:t=>i(t.target.value),children:[!d&&e.jsx("option",{value:"insert",children:"INSERT SQL"}),!d&&e.jsx("option",{value:"delete",children:"DELETE SQL"}),!d&&e.jsx("option",{value:"delete+insert",children:"DELETE + INSERT SQL"}),e.jsx("option",{value:"csv",children:"CSV"})]}),e.jsx(z,{label:"Batch Size",type:"number",value:s,onChange:t=>u(t.target.value)}),c==="csv"&&e.jsxs("div",{children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1 text-xs text-slate-400 hover:text-slate-200 transition-colors",onClick:()=>q(!b),children:[b?e.jsx(Y,{size:12}):e.jsx(Z,{size:12}),"Advanced CSV Options"]}),b&&e.jsxs("div",{className:"mt-3 flex flex-col gap-3 pl-4 border-l border-surface-700",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(C,{label:"Delimiter",value:y,onChange:t=>P(t.target.value),children:[e.jsx("option",{value:",",children:"Comma (,)"}),e.jsx("option",{value:";",children:"Semicolon (;)"}),e.jsx("option",{value:"\\t",children:"Tab"}),e.jsx("option",{value:"|",children:"Pipe (|)"}),e.jsx("option",{value:"custom",children:"Custom"})]}),y==="custom"&&e.jsx(z,{label:"Custom",value:I,onChange:t=>H(t.target.value.slice(0,1)),className:"w-16"})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(C,{label:"Quote Character",value:L,onChange:t=>W(t.target.value),children:[e.jsx("option",{value:'"',children:'Double Quote (")'}),e.jsx("option",{value:"'",children:"Single Quote (')"}),e.jsx("option",{value:"",children:"None"})]}),e.jsxs(C,{label:"Escape Character",value:T,onChange:t=>J(t.target.value),children:[e.jsx("option",{value:'"',children:'Double Quote (")'}),e.jsx("option",{value:"\\",children:String.raw`Backslash (\)`}),e.jsx("option",{value:"",children:"None"})]})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(C,{label:"Line Ending",value:M,onChange:t=>V(t.target.value),children:[e.jsx("option",{value:"crlf",children:"CRLF (Windows)"}),e.jsx("option",{value:"lf",children:"LF (Unix/Mac)"}),e.jsx("option",{value:"cr",children:"CR (Legacy Mac)"})]}),e.jsxs(C,{label:"Encoding",value:N,onChange:t=>X(t.target.value),children:[e.jsx("option",{value:"utf-8",children:"UTF-8"}),e.jsx("option",{value:"utf-8-sig",children:"UTF-8 with BOM"}),e.jsx("option",{value:"ascii",children:"ASCII"})]})]})]})]}),e.jsx("p",{className:"text-xs text-slate-500",children:p?e.jsxs(e.Fragment,{children:["Exporting ",e.jsxs("strong",{className:"text-slate-300",children:[p.rows.length," filtered rows"]})," from ",e.jsx("code",{className:"text-slate-300",children:r})," (grid filter active)."]}):j?e.jsxs(e.Fragment,{children:["Exporting ",e.jsxs("strong",{className:"text-slate-300",children:[j.length," selected rows"]})," from ",e.jsx("code",{className:"text-slate-300",children:r}),"."]}):e.jsxs(e.Fragment,{children:["Exports all rows from ",e.jsx("code",{className:"text-slate-300",children:r}),". Large tables are streamed in batches."]})})]})})}export{ae as default};
