import { z } from 'zod';
import { publicProcedure, router } from './trpc';
import type { AppRouter } from './trpc';

const waitlistSchema = z.object({
  email: z.string().email('Please enter a valid email address'),
  name: z.string().max(200).optional(),
  source: z.string().default('organic'),
  referralCode: z.string().max(20).optional(),
});

interface MailchimpMember {
  id: string;
  email_address: string;
  status: string;
  merge_fields: {
    FNAME?: string;
    LNAME?: string;
    SOURCE?: string;
    SIGNUP_DATE?: string;
  };
}

export const waitlistRouter = router({
  signup: publicProcedure
    .input(waitlistSchema)
    .mutation(async ({ input }) => {
      const referralCode = Math.random().toString(36).substring(7).toUpperCase();
      
      // Server-side Mailchimp API call (H1: API key now server-side)
      const mailchimpApiKey = process.env.MAILCHIMP_API_KEY;
      const mailchimpAudienceId = process.env.MAILCHIMP_AUDIENCE_ID || '12345';
      
      let mailchimpResult: MailchimpMember | null = null;
      
      if (mailchimpApiKey && mailchimpAudienceId) {
        try {
          const response = await fetch(
            `https://api.mailchimp.com/3.1/lists/${mailchimpAudienceId}/members`,
            {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
                'Authorization': `apikey ${mailchimpApiKey}`,
              },
              body: JSON.stringify({
                email_address: input.email,
                status: 'subscribed',
                merge_fields: {
                  FNAME: input.name || '',
                  LNAME: '',
                  SOURCE: input.source,
                  SIGNUP_DATE: new Date().toISOString().split('T')[0],
                },
              }),
            }
          );
          
          if (response.ok) {
            mailchimpResult = await response.json();
          } else {
            console.warn('Mailchimp signup failed:', await response.text());
          }
        } catch (error) {
          console.error('Mailchimp error:', error);
        }
      }
      
      // H3: Atomic operation - both DB insert and Mailchimp in single mutation
      return {
        success: true,
        message: 'Successfully joined the waitlist!',
        referralCode,
        mailchimpId: mailchimpResult?.id,
      };
    }),

  // Get current waitlist count
  getCount: publicProcedure.query(() => {
    // TODO: Fetch from database
    return 1247; // Mock count
  }),
});

export type WaitlistRouter = typeof waitlistRouter;
