import { PermissionsSchema } from "@shared";
import { createInsertSchema, createUpdateSchema } from "drizzle-zod";
import { z } from "zod";
import { schema } from "@/database";

export const SelectOrganizationRoleSchema = z.object({
  /**
   * The fact that we are setting id here explicitly (when it is coming from the database is a bit of a hack)
   * because for example in GET /api/roles, we are not only returning custom roles, but also predefined ones
   * (which don't have a UUID id, see generatePredefinedRole in organization-role.ts)
   */
  id: z.string(),
  organizationId: z.string(),
  role: z.string(),
  name: z.string(),
  description: z.string().nullable(),
  permission: PermissionsSchema,
  createdAt: z.coerce.date(),
  updatedAt: z.coerce.date().nullable(),
  /**
   * Whether or not the role is "predefined" (not a custom one) or not
   * This dictates to clients whether or not the role is mutable
   */
  predefined: z.boolean(),
});
export const InsertOrganizationRoleSchema = createInsertSchema(
  schema.organizationRolesTable,
  {
    permission: PermissionsSchema,
  },
).omit({
  id: true, // ID is generated by Better Auth, not provided by caller
});

export const UpdateOrganizationRoleSchema = createUpdateSchema(
  schema.organizationRolesTable,
  {
    permission: PermissionsSchema,
  },
).omit({
  role: true, // Role identifier is immutable, cannot be updated
});

export type OrganizationRole = z.infer<typeof SelectOrganizationRoleSchema>;
export type InsertOrganizationRole = z.infer<
  typeof InsertOrganizationRoleSchema
>;
export type UpdateOrganizationRole = z.infer<
  typeof UpdateOrganizationRoleSchema
>;
