import { createClientFromRequest } from 'npm:@base44/sdk@0.8.40';

const STR_MAX = 2000;
const NUM_MAX = 2000;
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const COOLDOWN_MS = 10 * 60 * 1000; // same email may re-submit once per 10 minutes
const GLOBAL_WINDOW_MS = 60 * 1000;
const GLOBAL_MAX = 8; // max 8 public intakes per minute globally

const str = (v, max = STR_MAX) => typeof v === 'string' ? v.slice(0, max) : '';
const num = (v) => {
  const n = Number(v);
  return Number.isFinite(n) && n > 0 && n < NUM_MAX ? n : undefined;
};

const FUNDING_MAP = {
  'Pay privately': 'Private payer',
  'Self-managed NDIS': 'Self-managed NDIS',
  'Plan-managed NDIS': 'Plan-managed NDIS',
  'NDIA-managed': 'NDIA-managed',
  'Request quote only': 'Quote-only',
  'Unsure': 'Quote-only',
};

Deno.serve(async (req) => {
  try {
    const base44 = createClientFromRequest(req);

    let body;
    try { body = await req.json(); } catch (_) { return Response.json({ error: 'Invalid request.' }, { status: 400 }); }
    const f = body?.form || {};

    // --- Server-side validation ---
    const full_name = str(f.full_name, 120).trim();
    const email = str(f.email, 200).trim().toLowerCase();
    if (!full_name) return Response.json({ error: 'Full name is required.' }, { status: 400 });
    if (!EMAIL_RE.test(email)) return Response.json({ error: 'A valid email is required.' }, { status: 400 });
    if (!f.declarations) return Response.json({ error: 'You must acknowledge the declarations.' }, { status: 400 });

    const phone = str(f.phone, 60);
    const postcode = str(f.postcode, 20);
    const contact_method = ['Email', 'Phone', 'SMS'].includes(f.contact_method) ? f.contact_method : 'Email';
    const side = ['Left', 'Right'].includes(f.side) ? f.side : 'Left';
    const level = str(f.level, 40);
    const limb = str(f.limb, 10);
    const prosthesisType = ['Socket', 'Osseointegration', 'Unsure'].includes(f.prosthesisType) ? f.prosthesisType : 'Socket';
    const manufacturer = str(f.manufacturer, 120);
    const model = str(f.model, 120);
    const funding = FUNDING_MAP[f.funding] || 'Quote-only';
    const ossiguardUse = ['Yes', 'No', 'Unsure'].includes(f.ossiguard?.use) ? f.ossiguard.use : 'Unsure';
    const ossiguardVersion = str(f.ossiguard?.version, 60);
    const measurements = f.measurements && typeof f.measurements === 'object' ? f.measurements : {};
    const sensitive = f.sensitive && typeof f.sensitive === 'object' ? f.sensitive : {};
    const design = f.design && typeof f.design === 'object' ? f.design : {};

    // --- Rate limiting ---
    // Global throttle: cap total public-intake projects created in the last minute.
    const since = new Date(Date.now() - GLOBAL_WINDOW_MS).toISOString();
    const recentGlobal = await base44.asServiceRole.entities.CoverProject.filter({ data_origin: 'Public Intake' }, '-created_date', GLOBAL_MAX + 1);
    const inWindow = (recentGlobal || []).filter((p) => p.created_date && p.created_date >= since).length;
    if (inWindow >= GLOBAL_MAX) {
      return Response.json({ error: 'We are receiving a lot of requests right now. Please try again in a moment.' }, { status: 429 });
    }

    // Per-email cooldown: prevent repeated submissions for the same address.
    const existingCustomers = await base44.asServiceRole.entities.Customer.filter({ email });
    const existingCustomer = (existingCustomers || [])[0] || null;
    if (existingCustomer) {
      const recentProjects = await base44.asServiceRole.entities.CoverProject.filter({ customer_uuid: existingCustomer.uuid }, '-created_date', 1);
      const last = (recentProjects || [])[0];
      if (last && last.created_date && new Date(last.created_date).getTime() > Date.now() - COOLDOWN_MS) {
        return Response.json({ error: 'A recent request from this email is already being reviewed. Please wait before submitting again.' }, { status: 429 });
      }
    }

    // --- Record creation (all server-side, service-role) ---
    const uuid = () => 'id-' + crypto.randomUUID();
    const today = new Date().toISOString().slice(0, 10);

    let customer = existingCustomer;
    if (!customer) {
      const customer_number = 'INTAKE-' + Date.now().toString(36).toUpperCase().slice(-6);
      customer = await base44.asServiceRole.entities.Customer.create({
        uuid: uuid(), customer_number, full_name, data_label: full_name,
        email, phone, address: postcode ? `Postcode ${postcode}` : '',
        preferred_contact_method: contact_method, funding_method: funding,
        approval_status: 'Quote requested', record_state: 'active', data_origin: 'Public Intake',
        ossiguard_status: ossiguardUse,
        ossiguard_version_known: ossiguardUse === 'Yes' ? ossiguardVersion : '',
      });
    }

    const configuration = `${side} ${level}`.trim();
    const limbProfile = await base44.asServiceRole.entities.LimbProfile.create({
      uuid: uuid(), customer_uuid: customer.uuid, profile_name: `${configuration} cover request`,
      configuration: configuration || 'Left Below-knee', side, amputation_level: level,
      interface_type: prosthesisType === 'Osseointegration' ? 'Osseointegration' : 'Socket',
      prosthesis_manufacturer: manufacturer, prosthesis_model: model, record_state: 'active',
    });

    const projectId = 'COVER-' + Date.now().toString(36).toUpperCase().slice(-6);
    const sensitiveKeys = ['scars', 'raised', 'pinch', 'pain', 'skinfold', 'noTouch', 'changes'];
    const sensitiveOn = sensitiveKeys.filter((k) => sensitive[k]);
    const sensitiveSummary = sensitiveOn.length ? `Flagged: ${sensitiveOn.join(', ')}. Notes: ${str(sensitive.notes) || '—'}` : 'None flagged';
    const designSummary = `${str(design.style)} · ${str(design.colour)}/${str(design.secondary)} · ${str(design.finish)} · vents ${str(design.vents)}${design.text ? ` · text "${str(design.text, 80)}"` : ''}${design.notes ? ` · ${str(design.notes)}` : ''}`;
    const ossiguardReview = ossiguardUse === 'Yes'
      ? `Existing Ossiguard reported (version ${ossiguardVersion || 'unknown'}). Workshop must verify fit and compatibility before reuse.`
      : 'Ossiguard Compatibility Review Required — customer did not confirm an existing SHiRE Ossiguard connector. Do not assume compatibility.';

    const project = await base44.asServiceRole.entities.CoverProject.create({
      uuid: uuid(), project_id: projectId, data_label: `${customer.full_name} — cover request`,
      customer_uuid: customer.uuid, limb_profile_uuid: limbProfile.uuid,
      status: 'Awaiting measurements', safety_boundary_accepted: true,
      prosthesis_configuration: configuration, measurement_method: 'Customer guided intake',
      sensitive_area_summary: sensitiveSummary, design_preferences: designSummary,
      ossiguard_attachment_method: ossiguardUse === 'Yes' ? 'SHiRE Ossiguard' : 'None',
      reason_for_cover: `Cosmetic cover requested via public intake. ${ossiguardReview}`,
      record_state: 'active', data_origin: 'Public Intake',
    });

    const session = await base44.asServiceRole.entities.MeasurementSession.create({
      uuid: uuid(), project_uuid: project.uuid, customer_uuid: customer.uuid,
      workflow: 'below-knee-cover', status: 'In progress', measured_date: today,
      notes: 'Customer-submitted guided measurements — verification required.', record_state: 'active',
    });

    const measures = [
      ['Cover overall length', measurements.coverLength],
      ['Calf width', measurements.calfWidth],
      ['Ankle width', measurements.ankleWidth],
      ['Foot length', measurements.footLength],
      ['Foot width', measurements.footWidth],
    ];
    for (const [name, val] of measures) {
      if (val !== '' && val != null) {
        await base44.asServiceRole.entities.EnvelopeStation.create({
          uuid: uuid(), component_uuid: 'pending', session_uuid: session.uuid,
          station_name: name, total_width_mm: name.includes('width') ? num(val) : undefined,
          height_from_origin_mm: name === 'Cover overall length' ? num(val) : undefined,
          notes: 'Customer-reported — verification required', entered_by: 'Customer intake', date_entered: today,
          shape_classification: 'Customer-Reported Measurement',
        });
      }
    }

    await base44.asServiceRole.entities.AuditEvent.create({
      uuid: uuid(), event_type: 'intake_submitted', record_type: 'CoverProject', record_uuid: project.uuid,
      actor_name: customer.full_name, summary: 'Public cover request submitted',
      details: `Limb: ${configuration}. Prosthesis: ${prosthesisType}. Funding: ${funding}.`,
    });

    return Response.json({ ok: true, intakeRef: projectId, customerName: customer.full_name });
  } catch (error) {
    return Response.json({ error: error?.message || 'Could not submit your request.' }, { status: 500 });
  }
});