import { collectPermissionScopes, userManagementPermissions } from "@tailor-platform/erp-kit/app";
import {
  defineConfig,
  defineAuth,
  defineIdp,
  defineStaticWebSite,
  definePlugins,
} from "@tailor-platform/sdk";
import { kyselyTypePlugin } from "@tailor-platform/sdk/plugin/kysely-type";
import { seedPlugin } from "@tailor-platform/sdk/plugin/seed";
import { user } from "@/modules-db";

const idp = defineIdp("default", {
  permission: {
    create: [{ conditions: [[{ user: "_loggedIn" }, "=", true]], permit: true }],
    read: [{ conditions: [[{ user: "_loggedIn" }, "=", true]], permit: true }],
    update: [{ conditions: [[{ user: "_loggedIn" }, "=", true]], permit: true }],
    delete: [{ conditions: [[{ user: "_loggedIn" }, "=", true]], permit: true }],
    sendPasswordResetEmail: [{ conditions: [[{ user: "_loggedIn" }, "=", true]], permit: true }],
  },
  clients: ["default"],
  userAuthPolicy: {
    allowSelfPasswordReset: true,
  },
  gqlOperations: "query",
});

const website = defineStaticWebSite("default-web", {
  description: "Default static website",
});

const auth = defineAuth("default", {
  userProfile: {
    type: user,
    usernameField: "email",
    attributes: {
      permissions: true,
    },
  },
  machineUsers: {
    developer: {
      attributes: {
        permissions: collectPermissionScopes(userManagementPermissions),
      },
    },
  },
  oauth2Clients: {
    default: {
      redirectURIs: ["http://localhost:5173", website.url],
      grantTypes: ["authorization_code", "refresh_token"],
      clientType: "public",
      requireDpop: true,
    },
  },
  idProvider: idp.provider(idp.name, "default"),
});

export default defineConfig({
  name: "template-app",
  cors: ["http://localhost:5173", website.url],
  db: {
    "main-db": {
      files: [`./src/modules-db.ts`],
      gqlOperations: "query",
    },
  },
  resolver: {
    "main-resolver": { files: [`./src/resolver/**/*.ts`] },
  },
  executor: { files: [`./src/executor/**/*.ts`] },
  auth: auth,
  idp: [idp],
  staticWebsites: [website],
});

export const plugins = definePlugins(
  kyselyTypePlugin({ distPath: "./src/generated/kysely-tailordb.ts" }),
  seedPlugin({ distPath: "./seed", machineUserName: "developer" }),
);
