# Marca blanca con SoundLinks: guía para la plataforma de la distribuidora

Este código va **en la plataforma de la distribuidora**, no en SoundLinks. Sirve para que cada smartlink creado por la API salga con el dominio maestro del cliente (ej. `links.midistro.com`).

## 0. Requisitos (una sola vez por cliente)

1. En SoundLinks, en **Dominios → Conectar dominio**, el cliente añade `links.midistro.com`.
2. En su proveedor de DNS crea este registro:

   | Tipo  | Nombre  | Valor                    |
   |-------|---------|--------------------------|
   | CNAME | `links` | `domains.soundlinks.ink` |

   > Importante: el CNAME apunta a **domains.soundlinks.ink** (no a soundlinks.ink).
   > Además, añade el registro TXT de verificación que muestra SoundLinks.
3. Cuando SoundLinks muestre el dominio como **Activo** (con SSL), ya se puede enviar en `domain`.
   Si el dominio no está activo en la cuenta, la API responde `400 "Ese dominio no está activo en la cuenta de la distribuidora"`.

---

## 1. Base de datos: tabla `WhiteLabel_Clients`

```sql
CREATE TABLE WhiteLabel_Clients (
  client_id           VARCHAR(36)  PRIMARY KEY,      -- UUID
  company_name        VARCHAR(200) NOT NULL,
  soundlinks_api_key  TEXT         NOT NULL,         -- guárdala cifrada (ver nota)
  master_domain       VARCHAR(253) NULL,            -- ej. links.midistro.com
  created_at          TIMESTAMP    DEFAULT CURRENT_TIMESTAMP,
  updated_at          TIMESTAMP    DEFAULT CURRENT_TIMESTAMP
);

-- Relación lógica: cada usuario pertenece a una distribuidora (cuenta matriz)
ALTER TABLE users ADD COLUMN client_id VARCHAR(36) NULL REFERENCES WhiteLabel_Clients(client_id);
```

**Nota de seguridad:** no guardes `soundlinks_api_key` en texto plano. Cífrala con una clave de tu `.env` (ej. AES-256-GCM), o guarda solo la referencia a tu gestor de secretos. Nunca la envíes al navegador.

Para saber qué dominio usar en un lanzamiento, se consulta la cuenta matriz del usuario:

```sql
SELECT c.master_domain, c.soundlinks_api_key
FROM users u JOIN WhiteLabel_Clients c ON c.client_id = u.client_id
WHERE u.id = :user_id;
```

---

## 2. Variables de entorno

```
SOUNDLINKS_API_URL=https://soundlinks.ink/api/v1
APP_ENCRYPTION_KEY=...   # para cifrar/descifrar soundlinks_api_key
```

---

## 3. Backend (Node.js / Express): guardar el dominio y crear lanzamientos

```js
// whitelabel.js
const express = require("express");
const router = express.Router();
const HOST_RE = /^(?=.{4,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/;

// Solo administradores o el dueño de la distribuidora
function canManage(req, clientId) {
  return req.user.role === "admin" || (req.user.role === "owner" && req.user.client_id === clientId);
}

router.get("/whitelabel/:clientId", async (req, res) => {
  if (!canManage(req, req.params.clientId)) return res.status(403).json({ error: "Sin permiso" });
  const c = await db.one("SELECT client_id, company_name, master_domain FROM WhiteLabel_Clients WHERE client_id=$1", [req.params.clientId]);
  res.json(c); // nunca devolver soundlinks_api_key
});

router.put("/whitelabel/:clientId", async (req, res) => {
  if (!canManage(req, req.params.clientId)) return res.status(403).json({ error: "Sin permiso" });
  const domain = String(req.body.master_domain || "").trim().toLowerCase().replace(/^https?:\/\//, "").replace(/\/.*$/, "");
  if (domain && !HOST_RE.test(domain)) return res.status(400).json({ error: "Dominio no válido (ej. links.midistro.com)" });
  await db.none("UPDATE WhiteLabel_Clients SET master_domain=$1, updated_at=NOW() WHERE client_id=$2", [domain || null, req.params.clientId]);
  res.json({ master_domain: domain });
});

module.exports = router;
```

### Inyección del dominio en el POST a SoundLinks

```js
// soundlinks.js
async function createSoundlinksRelease(userId, release) {
  const c = await db.one(
    `SELECT c.master_domain, c.soundlinks_api_key FROM users u
     JOIN WhiteLabel_Clients c ON c.client_id = u.client_id WHERE u.id = $1`, [userId]);

  const body = {
    upc: release.upc,                       // 8–14 dígitos
    account_id: String(userId),             // id del usuario en TU plataforma
    title: release.title,
    artists: release.artists,               // ["Artista 1", "Artista 2"]
    artist_name: release.mainArtist || "",
    release_at: release.releaseAt || null,  // "2026-07-01T00:00:00"
    release_tz: release.timezone || "America/Mexico_City",
    cover_url: release.coverUrl || "",
    type: release.type || "album",          // "track" | "album"
  };
  if (c.master_domain) body.domain = c.master_domain;   // inyección dinámica

  const r = await fetch(`${process.env.SOUNDLINKS_API_URL}/releases`, {
    method: "POST",
    headers: { "Content-Type": "application/json", "X-API-Key": decrypt(c.soundlinks_api_key) },
    body: JSON.stringify(body),
  });
  const data = await r.json();
  if (!r.ok) throw new Error(data.detail || `SoundLinks ${r.status}`);
  return data; // incluye la URL del smartlink con tu dominio
}
```

### Lo mismo en PHP (Laravel / PHP puro)

```php
function createSoundlinksRelease(PDO $db, int $userId, array $release): array {
  $st = $db->prepare("SELECT c.master_domain, c.soundlinks_api_key FROM users u
                      JOIN WhiteLabel_Clients c ON c.client_id = u.client_id WHERE u.id = ?");
  $st->execute([$userId]);
  $c = $st->fetch(PDO::FETCH_ASSOC);

  $body = [
    'upc' => $release['upc'], 'account_id' => (string)$userId, 'title' => $release['title'],
    'artists' => $release['artists'], 'release_at' => $release['release_at'] ?? null,
    'release_tz' => $release['timezone'] ?? 'America/Mexico_City', 'type' => $release['type'] ?? 'album',
  ];
  if (!empty($c['master_domain'])) $body['domain'] = $c['master_domain'];

  $ch = curl_init(getenv('SOUNDLINKS_API_URL') . '/releases');
  curl_setopt_array($ch, [
    CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'X-API-Key: ' . decrypt($c['soundlinks_api_key'])],
    CURLOPT_POSTFIELDS => json_encode($body),
  ]);
  $data = json_decode(curl_exec($ch), true);
  $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  if ($code >= 400) throw new Exception($data['detail'] ?? "SoundLinks $code");
  return $data;
}
```

---

## 4. Frontend (React): vista "Configuración de Marca Blanca"

Muéstrala en el menú solo si `user.role === "admin"` o `user.role === "owner"`.

```jsx
import { useEffect, useState } from "react";

export default function WhiteLabelSettings({ clientId }) {
  const [domain, setDomain] = useState("");
  const [msg, setMsg] = useState("");

  useEffect(() => {
    fetch(`/api/whitelabel/${clientId}`, { credentials: "include" })
      .then((r) => r.json()).then((c) => setDomain(c.master_domain || ""));
  }, [clientId]);

  const save = async (e) => {
    e.preventDefault();
    const r = await fetch(`/api/whitelabel/${clientId}`, {
      method: "PUT", credentials: "include",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ master_domain: domain }),
    });
    const d = await r.json();
    setMsg(r.ok ? "Guardado" : d.error);
  };

  return (
    <section>
      <h1>Configuración de Marca Blanca</h1>
      <form onSubmit={save}>
        <label htmlFor="master-domain">Dominio Maestro para Smartlinks (ej. links.midistro.com)</label>
        <input id="master-domain" value={domain} onChange={(e) => setDomain(e.target.value)} placeholder="links.midistro.com" />
        <button type="submit">Guardar</button>
        {msg && <p>{msg}</p>}
      </form>

      <div className="dns-help">
        <h3>Instrucciones DNS para tu equipo técnico</h3>
        <p>En el proveedor DNS de tu dominio crea este registro:</p>
        <pre>Tipo: CNAME   Nombre: links   Valor: domains.soundlinks.ink</pre>
        <p>Después conecta el mismo dominio en SoundLinks (Dominios) y añade el registro TXT de verificación que te indique.
           Cuando aparezca como "Activo" con SSL, todos los smartlinks nuevos saldrán con tu dominio.</p>
      </div>
    </section>
  );
}
```

---

## 5. Respuesta de SoundLinks y errores comunes

- `200`: devuelve `{ id, url, slug, upc, domain, upcoming, release_at, platforms, artist_id, created }`. `url` ya sale con el dominio maestro (`https://links.midistro.com/titulo`) y `created` es `false` si el UPC ya existía.
- Si se reenvía el mismo UPC, devuelve el lanzamiento existente; no crea duplicados.
- `400 Ese dominio no está activo...`: el dominio aún no está verificado o con SSL en la cuenta de SoundLinks.
- `401`: falta la cabecera `X-API-Key` o la clave fue revocada.
- Estadísticas: `GET /api/v1/releases/{upc}/stats?days=30` y `GET /api/v1/accounts/{account_id}/stats` (con la misma cabecera).
