"use server";
import {action, ActionError, userAction} from "@/lib/safe-actions/actions";
import {AgentSchema} from "@/features/agents/agents.schema";
import {z} from "zod";
import {eq, and, ne, count} from "drizzle-orm";
import {db} from "@/db";
import * as drizzleDb from "@/db";
import {slugify} from "@/utils/slugify";
import {getHealthLast12hLogs} from "@/db/services/healthcheck";

const verifySlugUniqueness = async (slug: string, agentId?: string) => {
    const conditions = agentId ? and(eq(drizzleDb.schemas.agent.slug, slug), ne(drizzleDb.schemas.agent.id, agentId)) : eq(drizzleDb.schemas.agent.slug, slug);
    const [countResult] = await db.select({count: count()}).from(drizzleDb.schemas.agent).where(conditions);
    if (countResult.count > 0) {
        throw new ActionError("Slug already exists");
    }
};



type CreateAgentInput = {
    organizationId?: string;
    data: z.infer<typeof AgentSchema>;
};

export async function createAgentService(input: CreateAgentInput) {
    const slug = slugify(input.data.name);

    await verifySlugUniqueness(slug);

    const [createdAgent] = await db
        .insert(drizzleDb.schemas.agent)
        .values({
            ...input.data,
            slug,
            organizationId: input.organizationId,
        })
        .returning();

    if (createdAgent && input.organizationId) {
        await db.insert(drizzleDb.schemas.organizationAgent).values({
            organizationId: input.organizationId,
            agentId: createdAgent.id,
        });
    }

    return createdAgent;
}




export const createAgentAction = userAction.schema(
    z.object({
        organizationId: z.string().optional(),
        data: AgentSchema,
    })
).action(async ({parsedInput}) => {
    const createdAgent = await createAgentService(parsedInput);
    return {
        data: createdAgent,
    };
});

export const updateAgentAction = userAction
    .schema(
        z.object({
            id: z.string(),
            data: AgentSchema,
        })
    )
    .action(async ({parsedInput}) => {
        const slug = slugify(parsedInput.data.name);
        await verifySlugUniqueness(slug, parsedInput.id);

        const [updatedAgent] = await db.update(drizzleDb.schemas.agent).set({
            ...parsedInput.data,
            slug: slug
        }).where(eq(drizzleDb.schemas.agent.id, parsedInput.id)).returning();

        return {
            data: updatedAgent,
        };
    });

export const getAgentAction = userAction.schema(z.string()).action(async ({parsedInput}) => {
    const agent = await db.query.agent.findFirst({
        where: eq(drizzleDb.schemas.agent.id, parsedInput),
        with: {
            databases: true
        }
    });

    return {
        data: agent,
        health: agent ? await getHealthLast12hLogs({ id: agent.id }) : []
    };
});

