import { test } from 'vitest';

import { db } from '../index.js';

test('throws if `user` is not set', async ({ expect }) => {
  // @ts-expect-error: missing required field
  await expect(() => db.apiToken.create({})).rejects.toThrowErrorMatchingInlineSnapshot(
    `[Error: Failed to create a new record with initial values: does not match the schema. Please see the schema validation errors above.]`,
  );
});

test('throws if an endpoint scope is invalid', async ({ expect }) => {
  let user = await db.user.create({});

  await expect(() =>
    db.apiToken.create({
      user,
      // @ts-expect-error: invalid endpoint scope
      endpointScopes: ['invalid'],
    }),
  ).rejects.toThrowErrorMatchingInlineSnapshot(
    `[Error: Failed to create a new record with initial values: does not match the schema. Please see the schema validation errors above.]`,
  );
});

test('happy path', async ({ expect }) => {
  let user = await db.user.create({});
  let session = await db.apiToken.create({ user });
  expect(session).toMatchInlineSnapshot(`
    {
      "crateScopes": null,
      "createdAt": "2017-11-19T17:59:22Z",
      "endpointScopes": null,
      "expiredAt": null,
      "id": 1,
      "lastUsedAt": null,
      "name": "API Token 1",
      "revoked": false,
      "token": "6270739405881613",
      "user": {
        "avatar": "https://avatars1.githubusercontent.com/u/14631425?v=4",
        "email": "user-1@crates.io",
        "emailVerificationToken": null,
        "emailVerified": true,
        "followedCrates": [],
        "githubLogin": "user-1",
        "id": 1,
        "isAdmin": false,
        "login": "user-1",
        "name": "User 1",
        "publishNotifications": true,
        "url": "https://github.com/user-1",
      },
    }
  `);
});
