import { getAdmin } from "../../../lib/admin-auth";
import { DB } from "../../../server/database.ts";
export default async function Jobs() {
  if (!(await getAdmin()))
    return (
      <main id="conteudo" className="admin-gate">
        <h1>Acesso reservado</h1>
      </main>
    );
  const jobs = await DB.prepare(
    "SELECT id,kind,status,attempts,available_at,last_error_code FROM outbox_jobs WHERE status!='DONE' ORDER BY created_at LIMIT 50",
  ).all<{
    id: string;
    kind: string;
    status: string;
    attempts: number;
    available_at: string;
    last_error_code: string | null;
  }>();
  return (
    <main id="conteudo" className="admin-shell">
      <a href="/administracao">← Inscrições</a>
      <h1>Processamento</h1>
      <p>
        Até 50 trabalhos pendentes ou com falha. O processamento é automático
        quando o agendamento está ativo.
      </p>
      <div className="admin-table-wrap">
        <table className="admin-table">
          <thead>
            <tr>
              <th>Trabalho</th>
              <th>Estado</th>
              <th>Tentativas</th>
              <th>Próxima tentativa</th>
              <th>Ação</th>
            </tr>
          </thead>
          <tbody>
            {jobs.results.map((j) => (
              <tr key={j.id}>
                <td>
                  {j.kind === "GENERATE_APPLICATION_PDF"
                    ? "Gerar PDF"
                    : "Enviar email"}
                </td>
                <td>
                  {j.status}
                  {j.last_error_code && <small> · {j.last_error_code}</small>}
                </td>
                <td>{j.attempts}</td>
                <td>{new Date(j.available_at).toLocaleString("pt-PT")}</td>
                <td>
                  {j.status === "FAILED" && (
                    <form
                      action={`/api/admin/jobs/${j.id}/retry`}
                      method="post"
                    >
                      <button>Voltar a tentar</button>
                    </form>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </main>
  );
}
