import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { getAllWorkspaces, upsertWorkspace, deleteWorkspace } from '@/lib/db/repositories';
import { withAuth } from '@/core/auth';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

const BrandKitSchema = z.object({
  version: z.number().int().default(1),
  header: z.object({
    phone: z.string().optional(),
    tagline: z.string().optional(),
  }).optional(),
  footer: z.object({
    mode: z.enum(['structured', 'mjml']).optional(),
    customMjml: z.string().optional(),
    legalFooterText: z.string().optional(),
    legalFooterTextEn: z.string().optional(),
    confidentialityNotice: z.string().optional(),
    confidentialityNoticeEn: z.string().optional(),
    showUnsubscribe: z.boolean().optional(),
    companyInfo: z.string().optional(),
    legalRegulations: z.string().optional(),
    complaintBodies: z.string().optional(),
    defaultSignature: z.string().optional(),
    defaultSignatureEn: z.string().optional(),
  }).optional(),
}).optional();

const BrandUpsertSchema = z.object({
  slug: z.string().min(1).regex(/^[a-z0-9-]+$/, 'slug muss lowercase mit Bindestrichen sein'),
  name: z.string().min(1),
  primaryColor: z.string().regex(/^#[0-9a-fA-F]{6}$/, 'Hex-Farbe wie #1a2b3c'),
  secondaryColor: z.string().regex(/^#[0-9a-fA-F]{6}$/).optional().nullable(),
  logoUrl: z.string().optional().nullable(),
  senderDomain: z.string().min(1),
  senderName: z.string().min(1),
  senderEmail: z.string().email(),
  replyToEmail: z.string().email(),
  footerText: z.string().min(1),
  brandVoice: z.string().min(1),
  wordingStyle: z.string().optional().nullable(),
  designStyle: z.string().optional().nullable(),
  companyId: z.number().int().optional().nullable(),
  /**
   * Shop-Domain für Login-Direktlinks (Kompass-Magic-Links). Optional —
   * Workspaces ohne Shop produzieren leere `{{LOGIN_LINK}}`-Substitution + Worker-Warning.
   * Akzeptiert mit oder ohne https://-Schema; `buildLoginLink()` normalisiert.
   * Leerstring → wird als null persistiert (Drizzle wandelt undefined→null durch Schema-Default).
   */
  shopDomain: z.string().url().or(z.literal('')).optional().nullable(),
  imprintUrl: z.string().url(),
  privacyUrl: z.string().url(),
  brandKit: BrandKitSchema,
  /**
   * Phase 3: Per-Workspace Email-Attribution-Settings.
   *  - attributionModel: Multi-Touch-Modell für diese Workspace
   *  - attributionLookbackDays: Touches älter als das werden ignoriert
   *  - webhookSecret: HMAC-Secret für /api/track/order-webhook (pro Workspace)
   *  - ga4PropertyId: optional, z.B. 'properties/123456789' oder nackte ID
   *  - cumasRecipientField: Dot-Path im Cumas-Order-Record (Workspace-Override über globales Setting)
   *  - activeConversionKinds: welche Conversion-Kinds in Stats zählen
   */
  attributionModel: z.enum(['last-click', 'first-click', 'linear', 'time-decay']).optional(),
  attributionLookbackDays: z.number().int().min(1).max(365).optional(),
  webhookSecret: z.string().regex(/^[A-Za-z0-9_-]{0,200}$/).optional().nullable(),
  ga4PropertyId: z.string().regex(/^[A-Za-z0-9/_-]{0,80}$/).optional().nullable(),
  cumasRecipientField: z.string().regex(/^[A-Za-z0-9_.\-]{0,120}$/).optional().nullable(),
  activeConversionKinds: z.array(z.enum(['order', 'lead', 'magic_login', 'form_submit'])).optional(),
});

export const GET = withAuth(async (req: NextRequest, _ctx) => {
  return NextResponse.json({ workspaces: getAllWorkspaces() });
});

export const POST = withAuth(async (req: NextRequest, _ctx) => {
  const body = await req.json();
  const parsed = BrandUpsertSchema.safeParse(body);
  if (!parsed.success) {
    const fieldErrors: Record<string, string> = {};
    for (const issue of parsed.error.issues) {
      const path = issue.path.join('.');
      if (path && !fieldErrors[path]) fieldErrors[path] = issue.message;
    }
    return NextResponse.json({
      error: 'Invalid workspace',
      issues: parsed.error.issues.map(i => `${i.path.join('.')}: ${i.message}`),
      fieldErrors,
    }, { status: 400 });
  }
  // brandKit landet im JSON-Sidecar; restliche Felder gehen direkt in die Tabelle.
  // Leere Strings für nullable-Felder → null (Drizzle akzeptiert null sauber).
  const { brandKit, ...rest } = parsed.data;
  const normalize = <T extends string | null | undefined>(v: T): T | null =>
    (v === '' ? null : v) as T | null;
  const workspace = upsertWorkspace({
    ...rest,
    webhookSecret: normalize(rest.webhookSecret) ?? undefined,
    ga4PropertyId: normalize(rest.ga4PropertyId) ?? undefined,
    cumasRecipientField: normalize(rest.cumasRecipientField) ?? undefined,
    brandKitJson: brandKit ?? { version: 1 },
  });
  return NextResponse.json({ ok: true, workspace });
});

export const DELETE = withAuth(async (req: NextRequest, _ctx) => {
  const slug = req.nextUrl.searchParams.get('slug');
  if (!slug) return NextResponse.json({ error: 'slug required' }, { status: 400 });
  const ok = deleteWorkspace(slug);
  return NextResponse.json({ ok });
});
