import {
  Controller,
  Header,
  Get,
  HttpService,
  Post,
  Body,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import Axios, { AxiosResponse } from 'axios';
import { map, flatMap, catchError } from 'rxjs/operators';
@Controller('signup')
export class MailchimpController {
  constructor(private httpService: HttpService) {}
  @Get()
  getList(): Observable<AxiosResponse> {
    const encodeToken = 'apikey 5233f0c2fb3f778d389a21f128804f84-us19';
    const headersRequest = {
      'Content-Type': 'application/json', // afaik this one is not needed
      Authorization: `${encodeToken}`,
    };
    const url = 'https://us19.api.mailchimp.com/3.0/lists';
    const lists = this.httpService
      .get(url, { headers: headersRequest })
      .pipe(map(response => response.data));
    return lists;
  }
  @Post()
  sendEmail(@Body() email_address) {
    const encodeToken = 'apikey 5233f0c2fb3f778d389a21f128804f84-us19';
    const headersRequest = {
      'Content-Type': 'text/plain', // afaik this one is not needed
      Authorization: `${encodeToken}`,
    };

    const options = {};

    const list_id = '97e3b408df';
    const data = {
      ...email_address,
      status: 'subscribed',
    };
    const op = JSON.stringify(data);

    const url = `https://us19.api.mailchimp.com/3.0/lists/${list_id}/members?skip_merge_validation=true`;

    const emailMessage = this.httpService.post(url, op, {
      headers: headersRequest,
    });

    emailMessage.subscribe(res => {});

    //, {headers:headersRequest});
  }
}
