import type { Request, Response } from "express";
import { z } from "zod";
import * as friends from "./service.js";

const sendSchema = z.object({ username: z.string().min(1) });

export async function list(req: Request, res: Response) {
  res.json({ friends: await friends.listFriends(req.userId!) });
}

export async function requests(req: Request, res: Response) {
  res.json(await friends.listRequests(req.userId!));
}

export async function search(req: Request, res: Response) {
  const q = String(req.query.q ?? "");
  res.json({ results: await friends.searchUsers(req.userId!, q) });
}

export async function sendRequest(req: Request, res: Response) {
  const { username } = sendSchema.parse(req.body);
  const result = await friends.sendRequest(req.userId!, username);
  res.status(201).json(result);
}

export async function accept(req: Request, res: Response) {
  await friends.acceptRequest(req.userId!, req.params.id);
  res.json({ ok: true });
}

export async function decline(req: Request, res: Response) {
  await friends.declineRequest(req.userId!, req.params.id);
  res.json({ ok: true });
}

export async function unfriend(req: Request, res: Response) {
  await friends.removeFriend(req.userId!, req.params.id);
  res.json({ ok: true });
}

export async function block(req: Request, res: Response) {
  await friends.blockFriend(req.userId!, req.params.id);
  res.json({ ok: true });
}
