'use server';

/**
 * @fileOverview Calculates net profit and profit margins based on income and expenses, and suggests optimization opportunities.
 *
 * - calculateProfit - A function that calculates the profit and provides optimization suggestions.
 * - ProfitCalculationInput - The input type for the calculateProfit function.
 * - ProfitCalculationOutput - The return type for the calculateProfit function.
 */

import {ai} from '@/ai/genkit';
import {z} from 'genkit';

const ProfitCalculationInputSchema = z.object({
  totalIncome: z.number().describe('The total income for the period.'),
  totalExpenses: z.number().describe('The total expenses for the period.'),
});
export type ProfitCalculationInput = z.infer<typeof ProfitCalculationInputSchema>;

const ProfitCalculationOutputSchema = z.object({
  netProfit: z.number().describe('The net profit calculated as total income minus total expenses.'),
  profitMargin: z.number().describe('The profit margin calculated as net profit divided by total income, expressed as a percentage.'),
  optimizationSuggestions: z
    .string()
    .describe('AI-generated suggestions for optimizing profit and minimizing costs.'),
});
export type ProfitCalculationOutput = z.infer<typeof ProfitCalculationOutputSchema>;

export async function calculateProfit(input: ProfitCalculationInput): Promise<ProfitCalculationOutput> {
  return calculateProfitFlow(input);
}

const prompt = ai.definePrompt({
  name: 'profitCalculationPrompt',
  input: {schema: ProfitCalculationInputSchema},
  output: {schema: ProfitCalculationOutputSchema},
  prompt: `You are an expert financial advisor for small businesses.

  Calculate the net profit and profit margin based on the provided income and expenses.
  Provide actionable suggestions for optimizing profit and minimizing costs.

  Total Income: {{totalIncome}}
  Total Expenses: {{totalExpenses}}

  Respond in the following format:
  {
    "netProfit": number,
    "profitMargin": number,
    "optimizationSuggestions": string
  }`,
});

const calculateProfitFlow = ai.defineFlow(
  {
    name: 'calculateProfitFlow',
    inputSchema: ProfitCalculationInputSchema,
    outputSchema: ProfitCalculationOutputSchema,
  },
  async input => {
    const {output} = await prompt(input);
    return output!;
  }
);
