import { pgTable, serial, integer, text, real, timestamp, unique, index } from 'drizzle-orm/pg-core';
import { users } from './auth';

// Per-user music favorites. `key` is an opaque path the app supplies and the server never interprets:
//   track  → homePath  "Music/<rel>/<file>"   (also the /stream path + RNTP queue id)
//   album  → music-rel "Albums/AC-DC/[1980] Back in Black"
//   artist → music-rel "Albums/AC-DC"
export const musicFavorites = pgTable(
  'music_favorites',
  {
    id: serial('id').primaryKey(),
    userId: integer('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
    kind: text('kind').notNull(), // 'track' | 'album' | 'artist'
    key: text('key').notNull(),
    createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
  },
  (t) => [
    unique('uq_music_favorites_user_kind_key').on(t.userId, t.kind, t.key),
    index('idx_music_favorites_user_kind').on(t.userId, t.kind),
  ],
);

// Per-user "currently playing" for resume-across-launch/device: the current track + playback position,
// plus a light metadata snapshot so the resume card renders before the library index has synced on a
// fresh device. `dir` is the folder to rebuild the album queue from ('' for a cross-album queue). One
// row per user (upserted; the app writes it throttled while playing and on pause/track-change/close).
export const musicNowPlaying = pgTable('music_now_playing', {
  userId: integer('user_id').primaryKey().references(() => users.id, { onDelete: 'cascade' }),
  homePath: text('home_path').notNull(),
  dir: text('dir').notNull().default(''),
  title: text('title').notNull().default(''),
  artist: text('artist').notNull().default(''),
  album: text('album').notNull().default(''),
  durationSec: real('duration_sec').notNull().default(0),
  positionSec: real('position_sec').notNull().default(0),
  updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
});
