import { createAction, Property } from '@activepieces/pieces-framework';
import { HttpMethod } from '@activepieces/pieces-common';
import { ninjapipeAuth } from '../../';
import { ninjapipeApiCall, flattenCustomFields, getAuth, ninjapipeCommon } from '../common';

export const createDeal = createAction({
  auth: ninjapipeAuth,
  name: 'create_deal',
  displayName: 'Create Deal',
  description: 'Creates a new deal.',
  audience: 'both',
  aiMetadata: { description: 'Creates a new deal (sales opportunity) in NinjaPipe, optionally tied to a pipeline, company, and contact, with value/currency, status, owner, and custom fields. Only Name is required. Not idempotent: each call adds another deal, so guard against duplicates.', idempotent: false },
  props: {
    name: Property.ShortText({ displayName: 'Name', required: true }),
    title: Property.ShortText({ displayName: 'Title', required: false }),
    status: Property.ShortText({ displayName: 'Status', required: false }),
    value: Property.Number({ displayName: 'Value', required: false }),
    currency: Property.ShortText({ displayName: 'Currency', description: 'e.g. EUR, USD', required: false }),
    owner: Property.ShortText({ displayName: 'Owner', required: false }),
    pipelineId: ninjapipeCommon.pipelineDropdown,
    companyId: ninjapipeCommon.companyDropdown,
    contactId: ninjapipeCommon.contactDropdown,
    notes: Property.LongText({ displayName: 'Notes', required: false }),
    customFields: Property.Object({ displayName: 'Custom Fields', required: false }),
  },
  async run(context) {
    const auth = getAuth(context);
    const p = context.propsValue;
    const body: Record<string, unknown> = {};
    if (p.name) body['name'] = p.name;
    if (p.title) body['title'] = p.title;
    if (p.status) body['status'] = p.status;
    if (p.value !== undefined) body['value'] = p.value;
    if (p.currency) body['currency'] = p.currency;
    if (p.owner) body['owner'] = p.owner;
    if (p.pipelineId) body['pipeline_id'] = p.pipelineId;
    if (p.companyId) body['company_id'] = p.companyId;
    if (p.contactId) body['contact_id'] = p.contactId;
    if (p.notes) body['notes'] = p.notes;
    if (p.customFields && typeof p.customFields === 'object') body['custom_fields'] = p.customFields;
    const response = await ninjapipeApiCall<Record<string, unknown>>({ auth, method: HttpMethod.POST, path: '/deals', body });
    return flattenCustomFields(response.body);
  },
});
