Spaces:
Sleeping

File size: 5,235 Bytes
2a2658a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
import express from "express";
import cors from "cors";
import multer from "multer";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import crypto from "crypto";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const app = express();
const PORT = process.env.PORT || 7860;

/* ========= CORS ========= */
const allow = [
  process.env.CLIENT_ORIGIN,
  process.env.ADMIN_ORIGIN,
].filter(Boolean);

app.use(cors({
  origin: (origin, cb) => {
    if (!origin) return cb(null, true);             // ferramentas, curl, etc.
    if (allow.length === 0 || allow.includes(origin)) return cb(null, true);
    return cb(new Error(`Origem não permitida: ${origin}`));
  },
  credentials: true
}));
app.use(express.json({ limit: "10mb" }));

/* ========= Storage simples (arquivos JSON) ========= */
const DATA_DIR = path.join(__dirname, "data");
const UPLOAD_DIR = path.join(__dirname, "uploads");
if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR, { recursive: true });
if (!fs.existsSync(UPLOAD_DIR)) fs.mkdirSync(UPLOAD_DIR, { recursive: true });

function fileOf(name) { return path.join(DATA_DIR, `${name}.json`); }
function readList(name) {
  const f = fileOf(name);
  if (!fs.existsSync(f)) return [];
  try { return JSON.parse(fs.readFileSync(f, "utf-8")); }
  catch { return []; }
}
function writeList(name, arr) {
  fs.writeFileSync(fileOf(name), JSON.stringify(arr, null, 2));
}
function genId() { return crypto.randomUUID(); }
function nowISO() { return new Date().toISOString(); }

function applyOrdering(list, ordering) {
  if (!ordering) return list;
  const desc = ordering.startsWith("-");
  const key = desc ? ordering.slice(1) : ordering;
  return [...list].sort((a, b) => {
    const av = a[key], bv = b[key];
    if (av == null && bv == null) return 0;
    if (av == null) return desc ? 1 : -1;
    if (bv == null) return desc ? -1 : 1;
    if (av < bv) return desc ? 1 : -1;
    if (av > bv) return desc ? -1 : 1;
    return 0;
  });
}
function filterExact(list, query) {
  // filtros exatos ?campo=valor (ignora "ordering")
  const entries = Object.entries(query || {}).filter(([k]) => k !== "ordering");
  if (!entries.length) return list;
  return list.filter(item =>
    entries.every(([k, v]) => String(item?.[k]) === String(v))
  );
}

/* ========= Upload ========= */
const storage = multer.diskStorage({
  destination: (_, __, cb) => cb(null, UPLOAD_DIR),
  filename: (_, file, cb) => {
    const ext = path.extname(file.originalname) || "";
    const base = path.basename(file.originalname, ext).replace(/[^\w.-]+/g, "_");
    cb(null, `${Date.now()}_${base}${ext}`);
  }
});
const upload = multer({ storage });

app.use("/uploads", express.static(UPLOAD_DIR));

app.post("/upload", upload.single("file"), (req, res) => {
  if (!req.file) return res.status(400).json({ error: "file obrigatório" });
  const file_url = `${req.protocol}://${req.get("host")}/uploads/${req.file.filename}`;
  res.json({ file_url });
});

/* ========= Auth (mock simples; plugue JWT aqui se quiser) ========= */
app.get("/auth/me", (req, res) => {
  // Ex.: validar Authorization: Bearer <token> com process.env.JWT_SECRET
  res.json({ role: "admin", email: "admin@example.com", name: "Admin" });
});

/* ========= Factory CRUD ========= */
function mountCrud(resource) {
  // GET /resource
  app.get(`/${resource}`, (req, res) => {
    let rows = readList(resource);
    rows = filterExact(rows, req.query);
    rows = applyOrdering(rows, req.query.ordering);
    res.json(rows);
  });

  // POST /resource
  app.post(`/${resource}`, (req, res) => {
    const rows = readList(resource);
    const item = req.body || {};
    if (!item.id) item.id = genId();
    if (!item.created_at) item.created_at = nowISO();
    rows.push(item);
    writeList(resource, rows);
    res.status(201).json(item);
  });

  // PUT /resource/:id
  app.put(`/${resource}/:id`, (req, res) => {
    const rows = readList(resource);
    const { id } = req.params;
    const i = rows.findIndex(r => String(r.id) === String(id));
    if (i < 0) return res.status(404).json({ error: "not found" });
    rows[i] = { ...rows[i], ...req.body, id };
    writeList(resource, rows);
    res.json(rows[i]);
  });

  // DELETE /resource/:id
  app.delete(`/${resource}/:id`, (req, res) => {
    const rows = readList(resource);
    const next = rows.filter(r => String(r.id) !== String(req.params.id));
    writeList(resource, next);
    res.json({ ok: true });
  });

  // GET /resource/filter  → { data: [...] } (compat com seu AdminAgendamentos)
  app.get(`/${resource}/filter`, (req, res) => {
    let rows = readList(resource);
    rows = filterExact(rows, req.query);
    rows = applyOrdering(rows, req.query.ordering);
    res.json({ data: rows });
  });
}

/* ========= Registra seus 5 recursos ========= */
[
  "agendamentos",   // API agendamento
  "barbeiros",      // API barbeiro
  "produtos",       // API produto
  "servicos",       // API serviço
  "vendas"          // API venda
].forEach(mountCrud);

/* ========= Saúde ========= */
app.get("/", (_, res) => res.send("OK - BaseBarber API"));

app.listen(PORT, () => console.log(`API rodando na porta ${PORT}`));